Java Recursive/Iterative


  • 0

    Iterative

    public class Solution {
        public int sumOfLeftLeaves(TreeNode root) {
            
            //iterative way
            if(root == null) {
                return 0;
            }
            
            Stack<TreeNode> stack = new Stack<>();
            stack.push(root);
            
            int sum = 0;
            
            while(!stack.empty()) {
                
                TreeNode node = stack.pop();
                TreeNode leftNode = node.left;
                
                if(leftNode != null) {
                    
                    if(leftNode.left == null && leftNode.right == null) {// left leaf
                        sum += leftNode.val;
                    } else {// not left leaf
                        stack.push(leftNode);
                    }
                }
                
                if(node.right != null) {
                    stack.push(node.right);
                }
            }
            
            return sum;
        }
    }
    

    Recursive

    public class Solution {
        public int sumOfLeftLeaves(TreeNode root) {
            
            if(root == null) {
                return 0;
            }
            
            int res = 0;
            
            TreeNode leftNode = root.left;
            if(leftNode != null) {
                
                if(leftNode.left == null && leftNode.right == null) {// left leaf
                    res += leftNode.val;
                } else {// not a left leaf
                    res += sumOfLeftLeaves(leftNode);
                }
            }
            
            res += sumOfLeftLeaves(root.right);
            return res;
            
        }
    }
    
    

Log in to reply
 

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