Simple java| bottom up recursive code


  • 1
    L
    public int sumOfLeftLeaves(TreeNode root) {
          return leafSumHelper(root, false);
        }
    
        private int leafSumHelper(TreeNode node, boolean isLeft) {
            if(node == null)
                return 0;
            if(node.left == null && node.right == null) {
                return isLeft ? node.val: 0;
            }
    
            return leafSumHelper(node.left, true) + leafSumHelper(node.right, false);
        }
    

  • 0
    L

    Iterative approach, using an explicit stack.

     public int sumOfLeftLeaves(TreeNode root){
            Stack<TreeNode> stack = new Stack<>();
    
            TreeNode curr = root;
            int sum = 0;
            while(!stack.isEmpty() || curr != null){
                while(curr != null){
                    stack.push(curr);
                    curr = curr.left;
                    if(isLeaf(curr)) {
                        sum += curr.val;
                    }
                }
    
                curr = stack.pop();
                curr = curr.right;
            }
    
            return sum;
        }
    
        private boolean isLeaf(TreeNode curr){
            return curr != null && curr.left == null && curr.right == null;
        }
    
    

Log in to reply
 

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