Java Recursion, easy to understand


  • 0
    T
    public class Solution {
        int max = 0;
        
        public int diameterOfBinaryTree(TreeNode root) {
            helper(root);
            return max;
        }
        
        private int helper(TreeNode root) {
            if (root == null) {
                return 0;
            }
            
            int left = root.left == null ? 0 : 1 + helper(root.left);
            int right = root.right == null ? 0 : 1 + helper(root.right);
            
            max = Math.max(max, left + right);
            
            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.