Bottom-up Solution


  • 0
    T
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        
        int max = 0;
        
        public int diameterOfBinaryTree(TreeNode root) {
            helper(root);
            return max;
        }
        
        private int helper(TreeNode root){
            if(null == root)
                return 0;
            int left = helper(root.left) + (root.left == null ? 0 : 1);
            int right = helper(root.right) + (root.right == null ? 0 : 1);
            max = Math.max(left + right,max);
            return Math.max(left,right);
        }
    }
    

Log in to reply
 

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