leetcode543.二叉树的直径

给你一棵二叉树的根节点,返回该树的 直径 。

二叉树的 直径 是指树中任意两个节点之间最长路径的 长度 。这条路径可能经过也可能不经过根节点 root 。

两节点之间路径的 长度 由它们之间边数表示。

示例 1:

leetcode543.二叉树的直径_第1张图片

输入:root = [1,2,3,4,5]
输出:3
解释:3 ,取路径 [4,2,1,3] 或 [5,2,1,3] 的长度。

示例 2:

输入:root = [1,2]
输出:1

提示:树中节点数目在范围 [1, 104] 内

思路: leetcode104.二叉树的最大深度-CSDN博客进阶版·,左右子树深度之和就是经过当前节点的当前最大直径// 左右子树深度之和就是经过当前节点的当前最大直径


    int length=0;
    public int diameterOfBinaryTree(TreeNode root) {
        depth(root,0);
        return length;

    }
    public int depth(TreeNode root,int height){
        if(root!=null){
            height++;
            int left=depth(root.left,0);
            int right=depth(root.right,0);
            height+=Math.max(left,right);
            // 左右子树深度之和就是经过当前节点的当前最大直径
            if(left+right>length)
                length=depth(root.left,0)+depth(root.right,0);
        }

        return height;
    }
}

你可能感兴趣的:(#,二叉树,算法,数据结构)