Sum of Left Leaves - Java, O(1) space and O(n) Recursive solution


  • 0
    V
        private boolean isLeaf(TreeNode root) {
            return root.left==null && root.right==null ? true : false;
        }
        private int sum(TreeNode root, boolean isRight) {
            if( root==null ) return 0;
            if( !isRight && isLeaf(root) ) return root.val;
            return sum(root.left, false) + sum(root.right, true);
        }
        public int sumOfLeftLeaves(TreeNode root) {
            return sum(root, true);
        }
    

    Explanation:
    For each node n:
    If n is a leaf node and is not the right child of its parent, then -
    sum = sum + n
    Else, continue visiting n.left and n.right


Log in to reply
 

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