DataStructure_Algorithm_HandBook_PreForLeetCode

404. Sum of Left Leaves

Given the root of a binary tree, return the sum of all left leaves.

A leaf is a node with no children. A left leaf is a leaf that is the left child of another node.

Example 1:

img

Input: root = [3,9,20,null,null,15,7]
Output: 24
Explanation: There are two left leaves in the binary tree, with values 9 and 15 respectively.

Example 2:

Input: root = [1]
Output: 0

Constraints:

class Solution {
    public int sumOfLeftLeaves(TreeNode root) {
        dfs(root);
        return sum;
    }
    int sum ; 
    void dfs(TreeNode node){
        if(node == null)  return;
        if(node.left != null && node.left.left  == null && node.left.right ==null){
            sum += node.left.val; 
        }
        dfs(node.left);
        dfs(node.right);
    }
}
class Solution {
    public int sumOfLeftLeaves(TreeNode root) {
        Deque<TreeNode> q = new LinkedList(); 
        if(root!= null) q.offer(root);
        int sum = 0;
        while(!q.isEmpty()){
            int size = q.size();
            for(int i = 0; i<size;i++){
                TreeNode node  = q.poll();
                if(node.left!=null && node.left.left == null && node.left.right == null){
                    sum += node.left.val;
                }
                if(node.left!=null) q.offer(node.left);
                if(node.right!=null)q.offer(node.right);
            }
        }
        return sum;
    }
}