Java solution


  • 0
    U
    private int max = Integer.MIN_VALUE;
    
    public int diameterOfBinaryTree(TreeNode root) {
        helper(root);
        return max <= 1 ? 0 : max - 1;
    }
    
    private int helper(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int left = helper(root.left);
        int right = helper(root.right);
        max = Math.max(max, left + right + 1);
        return Math.max(left, right) + 1;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.