function [maxheight,cost] = CalcTreeHeight(stree,D)
% CalcTreeHeight -- Measure the total height of a stat-tree
%  Usage
%    [maxheight, cost] = CalcTreeHeight(stree,D)
%  Inputs
%    stree       stat tree (e.g. generated by CalcStatTree)
%    D           maximum depth of search
%  Outputs
%    maxheight   Height of the tree, assigning to each branch a length
%                equal to the entropy drop between parent and child
%    cost        Tree of entropy drops associated with various splits
%
%  Description
%    This is a utility used by PlotBasisTree to set scale for plotting
%    It is not intended for other use.
%
%  See Also
%    CalcStatTree, PlotBasisTree
%

    cost = zeros(size(stree));
    value = stree;
    % prune, bottom-UpSample, left-right scan
    for d=D-1:-1:0,
       for b=0:(2^d-1),
            vparent = stree(node(d,b));
            vchild  = value(node(d+1,2*b)) + value(node(d+1,2*b+1));
            if(vparent < vchild),
                value(node(d,b)) = vparent;
                cost(node(d,b))  = 0. ;
            else
                value(node(d,b)) = vchild;
                cost(node(d,b))  = vparent - vchild;
            end
       end
    end
    height = cost .* 0;
    % prune, bottom-UpSample, left-right scan
    for d=D-1:-1:0,
       for b=0:(2^d-1),
            delta = cost(node(d,b));
            if(delta == 0)
                height(node(d,b)) = 0;
            else
                height(node(d,b)) = delta + ...        
                        max(height(node(d+1,2*b)),height(node(d+1,2*b+1)));
            end
       end
    end
    maxheight = height(1);

%
% Copyright (c) 1993. David L. Donoho
%    
    
    
 
 
%
%  Part of Wavelab Version 850
%  Built Tue Jan  3 13:20:40 EST 2006
%  This is Copyrighted Material
%  For Copying permissions see COPYING.m
%  Comments? e-mail wavelab@stat.stanford.edu 
