首页 > 其他 > 详细

543.二叉树的直径--递归调用

时间:2020-03-10 15:54:07      阅读:44      评论:0      收藏:0      [点我收藏+]

这道题思路很简单,找到左右子树的层数之和然后加一即可,但问题出在我不会表达出函数的递归调用,还有如何更新计数的问题。

class Solution {
    int ans;
    int depth(TreeNode* rt){
        if (rt == NULL) return 0; // 访问到空节点了,返回0
        int L = depth(rt->left); // 左儿子为根的子树的深度
        int R = depth(rt->right); // 右儿子为根的子树的深度
        ans = max(ans, L + R + 1); // 计算d_node即L+R+1 并更新ans
        return max(L, R) + 1; // 返回该节点为根的子树的深度
    }
public:
    int diameterOfBinaryTree(TreeNode* root) {
        ans = 1;
        depth(root);
        return ans - 1;
    }
};

 

543.二叉树的直径--递归调用

原文:https://www.cnblogs.com/learn-with-blog/p/12455528.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!