543二叉树的直径

题目描述

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

示例 :
给定二叉树
1
/
2 3
/ \
4 5
返回 3, 它的长度是路径 [4,2,1,3] 或者 [5,2,1,3]。
注意:两结点之间的路径长度是以它们之间边的数目表示。

思路分析

最开始思路正确找子树的高度和的max,但坑人之处在于,最长的路径不一定必须要经过根节点。所以要对从root开始的每一个点遍历,找到左右子树的高度和的max。

代码实现

 private int max = Integer.MIN_VALUE;

    /**
     * 对每一个点都要遍历
     *
     * @param root
     * @return
     */
    public int diameterOfBinaryTree(TreeNode root) {
        if (root == null) {
            return 0;
        }
        getDepth(root);
        return max;
    }

    public int getDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }

        int depth1 = getDepth(root.left);
        int depth2 = getDepth(root.right);
        if (depth1 + depth2 > max) {
            max = depth1 + depth2;
        }
        return Math.max(depth1, depth2) + 1;
    }
发布了71 篇原创文章 · 获赞 3 · 访问量 2426

猜你喜欢

转载自blog.csdn.net/qq_34761012/article/details/104278315
今日推荐