Java Iterative and Recursive


  • 0
    C

    public class Solution {
    public int sumOfLeftLeaves(TreeNode root) {

        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.offer(root);
        int sum = 0;
        while(!queue.isEmpty()){
            TreeNode node = queue.poll();
            if(node == null) continue;
            if(node.left != null && node.left.right == null && node.left.left == null){
                sum += node.left.val;
            } else {
                queue.offer(node.left);
            }
            queue.offer(node.right);
        }
        return sum;
    }
    

    }

    public class Solution {
    public int sumOfLeftLeaves(TreeNode root) {
    if(root == null){
    return 0;
    }
    int l = root.left == null ? 0 : root.left.left == null && root.left.right == null ? root.left.val : sumOfLeftLeaves(root.left);
    int r = root.right == null ? 0 : root.right.left == null && root.right.right == null ? 0 : sumOfLeftLeaves(root.right);
    return l + r;
    }
    }


Log in to reply
 

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