二叉树的直径

基本思路:

(1)求每个节点左右子树的深度,则进过该节点的最大length=ldeep+rdeep;

(2)取最大的length即为二叉树的直径

当然这个算法性能不好,但思路很简单,这次也采用递归算法,如果要求采用非递归的话,首先需要改动的是TreeDeep,然后FindMax这个实际上市递归遍历每个节点,可以用遍历的非递归形式替换即可。(如果有人想要看非递归又不会,给我留言,我就添加上)

这个问题一个延伸,就是输出最长路径

给出一个思路抛砖引玉:在FindMaxLen函数外面添加一个全局变量BitTree finalroot;

修改MaxLen=处的代码为

if(temp>MaxLen){

  MaxLen=temp;

     finalroot=root;

}

当FindMaxLen结束后,finalroot就是最长路径的根节点,同时呢我们可以可到左右子树的深度的值,为了得到路径,采用后续非递归遍历,根据栈的深度就可以知道左右子树的路径,原因是进栈的首先是左子树,当栈的高度和左子树深度相同时,栈内的节点就是路径,当从左子树返回时,开始进入右子树,当栈达到右子树深度时就是右边的路径,也就是整个路径分两次输出出来。

int FindMaxLen(BinTree root){
     static int MaxLen=0;//用来保存最大长度
     if(root){    
         int temp=TreeDeep(root->lchild)+TreeDeep(root->rchild);
         MaxLen=temp>MaxLen?temp:MaxLen;
         FindMaxLen(root->lchild);
         FindMaxLen(root->rchild);
     }
     return MaxLen;
}
int TreeDeep(BinTree root){
     int deep=0;
     if(root){
         int lchilddeep=TreeDeep(root->lchild);
         int rchilddeep=TreeDeep(root->rchild);
         deep=lchilddeep>rchilddeep?lchilddeep+1:rchilddeep+1;
     }
     return deep;
}

原文地址:https://www.cnblogs.com/GoAhead/p/2517937.html