Java Solution


  • 0
    M
    public int diameterOfBinaryTree(TreeNode root) {
    
        if(root==null) return 0;
    
    		//the path goes through the root
    		int len1 = height(root.left) + height(root.right) ;
    
    		//the path does not pass the root
    		int len2 = Math.max(diameterOfBinaryTree(root.left), diameterOfBinaryTree(root.right));
    
    		return Math.max(len1, len2);
    	}
    	public int height(TreeNode root) {
    		if(root == null) 
    			return 0;
    		/* compute the depth of each subtree */
    		int leftDepth = height(root.left);
    		int rightDepth = height(root.right);
    		return (leftDepth > rightDepth) ? leftDepth + 1 : rightDepth + 1;
    	} 
    

Log in to reply
 

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