zoukankan      html  css  js  c++  java
  • 【LeetCode】543. 二叉树的直径

    题目链接:

    543. 二叉树的直径

    题目描述:

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

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

    示例:

    给定二叉树:

             1
            / 
           2   3
          /      
         4   5    
    

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

    思路:

    首先需要明确二叉树的直径是什么,不然就容易犯这样的错误:直径 = 左子树高度 + 右子树高度

    题目中已经说明:二叉树的直径长度是任意两个结点路径长度中的最大值。也就是说,这条路径可能经过根结点,也可能不经过根节点。

    二叉树

    如图所示,左子树高度 + 右子树高度 = 7,而正确答案应该是 8。直径最长路径之一:[1, 0, 6, 8, 9, 7, 6, 9, 2]

    因此不能简单地将根节点的左右子树高度相加,而应该遍历所有节点,记录以此节点为根的子树的直径:左子树高度 + 右子树高度,取最大值。

    root的直径 = root左子树高度 + root右子树高度

    root的高度 = max {root左子树高度, root右子树高度} + 1

    代码实现:

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        int result = 0;
    
        public int diameterOfBinaryTree(TreeNode root) {
            depth(root);
            return result;
        }
        
        private int depth(TreeNode node) {
            // 递归出口
            if (node == null) {
                return 0;
            }
            // 递归
            int leftDepth = depth(node.left);
            int rightDepth = depth(node.right);
            result = Math.max(result, leftDepth + rightDepth);
            // 返回以此节点为根的树的深度
            return Math.max(leftDepth, rightDepth) + 1;
        }
    }
    
  • 相关阅读:
    react路由组件&&非路由组件
    react函数式组件(非路由组件)实现路由跳转
    react使用antd组件递归实现左侧菜单导航树
    【LeetCode】65. Valid Number
    【LeetCode】66. Plus One (2 solutions)
    【LeetCode】68. Text Justification
    【LeetCode】69. Sqrt(x) (2 solutions)
    【LeetCode】72. Edit Distance
    【LeetCode】73. Set Matrix Zeroes (2 solutions)
    【LeetCode】76. Minimum Window Substring
  • 原文地址:https://www.cnblogs.com/ME-WE/p/12454813.html
Copyright © 2011-2022 走看看