543.二叉树的直径

给定一棵二叉树,你需要计算它的直径长度。一棵二叉树的直径长度是任意两个结点路径长度中的最大值。这条路径可能穿过根结点。

示例 :

给定二叉树

          1
         / \
        2   3
       / \     
      4   5    

返回 3, 它的长度是路径 [4,2,1,3] 或者 [5,2,1,3]。

注意:两结点之间的路径长度是以它们之间边的数目表示。

int calMaxRoot(struct TreeNode* root, int *maxRoot){
    if (NULL == root) return 0;
    int lLen = calMaxRoot(root->left, maxRoot);
    int rLen = calMaxRoot(root->right, maxRoot);
    if (lLen + rLen > *maxRoot) *maxRoot = lLen + rLen;
    return (lLen > rLen ? lLen : rLen) + 1;
}

int diameterOfBinaryTree(struct TreeNode* root){
    int maxRoot = 0;
    calMaxRoot(root, &maxRoot);
    return maxRoot;
}
发布了28 篇原创文章 · 获赞 18 · 访问量 3756

猜你喜欢

转载自blog.csdn.net/Aaron_Kings/article/details/101645068
今日推荐