1181. 二叉树的直径

 
给定一颗二叉树,您需要计算树的直径长度。 二叉树的直径是树中任意两个节点之间最长路径的长度。 此路径不一定会通过树根。

样例

样例 1:
给定一棵二叉树
1
/ \
2 3
/ \
4 5
返回3, 这是路径[4,2,1,3] 或者 [5,2,1,3]的长度.
样例 2:
输入:[2,3,#,1]
输出:2
 
解释:
2
/
3
/
1

注意事项

两个节点之间的路径长度由它们之间的边数表示。
 
/**
* Definition of TreeNode:
* public class TreeNode {
*     public int val;
*     public TreeNode left, right;
*     public TreeNode(int val) {
*         this.val = val;
*         this.left = this.right = null;
*     }
* }
*/
 
 
public class Solution {
    /**
     * @param root: a root of binary tree
     * @return: return a integer
     */
    public int diameterOfBinaryTree(TreeNode root) {
        // write your code here
        if (root == null ) return 0;
        int sub = Math.max(diameterOfBinaryTree(root.left), diameterOfBinaryTree(root.right));
        return Math.max(sub, helper(root.left) + helper(root.right));
    }
        
    int helper(TreeNode node) {
            if (node == null ) return 0;
            return 1 + Math.max(helper(node.left), helper(node.right));
    }
}
 
Logo

北京人形旗下天工造物具身智能开源社区,聚焦具身天工与慧思开物两大平台

更多推荐