Java recursion with global max clear comments


  • 0
    public class Solution {
        int max = 0; // global max of length going through a node connecting both left and right subtrees.
        public int diameterOfBinaryTree(TreeNode root) {
            return Math.max(diameterOfBinaryTreeHelper(root), max);
            //return Math.max(max, diameterOfBinaryTreeHelper(root)); is wrong as max is updated after calling helper method.
        }
        
        // returns max length ending with root
        private int diameterOfBinaryTreeHelper(TreeNode root) {
            if (root == null) {
                return -1;
            }
            int maxLeft = diameterOfBinaryTreeHelper(root.left) + 1;
            int maxRight = diameterOfBinaryTreeHelper(root.right) + 1;
            max = Math.max(max, maxLeft + maxRight);
            return Math.max(maxLeft, maxRight);
        }
    }

Log in to reply
 

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