您的位置:首页 > 其它

求二叉树中节点的最大距离

2015-07-26 20:15 246 查看
编程之美中的题目,但是书上的代码递归太复杂,整理了个优化的解法:

思路: 可以转换为求二叉树中任意一个节点左右子树的高度和

struct Node{
Node *pLeft;
Node *pRight;
};

int maxLen = 0;

int treeDepth(Node *pRoot, &maxLen){
if(pRoot == NULL)
return -1;
int leftDepth = treeDepth(pRoot->pLeft, maxLen) + 1;
int rightDepth = treeDepth(pRoot->pRight, maxLen) + 1;
if(maxLen < leftDepth + rightDepth)
maxLen = leftDepth + rightDepth;
return leftDepth > rightDepth ? leftDepth : rightDepth;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: