3月打卡活动第10天 LeetCode第543题:二叉树的直径(简单)

3月打卡活动第10天 LeetCode第543题:二叉树的直径(简单)

  • 题目:给定一棵二叉树,你需要计算它的直径长度。一棵二叉树的直径长度是任意两个结点路径长度中的最大值。这条路径可能穿过根结点。
    在这里插入图片描述

  • 题解做法:没太做过二叉树的题,虽然是简单难度,但是拿到手还有有点懵懵的。。。看了题解做法,感觉好像也用到什么没见过的函数。。下次二叉树一定加油做出来!

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

作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/diameter-of-binary-tree/solution/er-cha-shu-de-zhi-jing-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

在这里插入图片描述

发布了100 篇原创文章 · 获赞 12 · 访问量 2358

猜你喜欢

转载自blog.csdn.net/new_whiter/article/details/104767277
今日推荐