404. Sum of Left Leaves

Find the sum of all left leaves in a given binary tree.

Example:

3

/ \
9 20
/ \
15 7

There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.

思路: 求所有左叶子节点的和,我们需要判断该节点是否是叶子节点,如果是就加和。判断left leaf的要求就是: parent.left = cur&&cur.left==null&&cur.right==null; 这里我们可以用in-order traversal的方法去记录parent,在cur入栈之前先判断parent.left!=null, 则parent=cur; 等到pop的时候,我们就去查left node的条件就可以加入sum。

public class Solution {
    public int sumOfLeftLeaves(TreeNode root) {
        int sum = 0;
        TreeNode cur = root;
        TreeNode parent = root;
        Stack<TreeNode> stack = new Stack<>();
        while(cur!= null || !stack.isEmpty()) {
            if (cur != null) {
                if (cur.left != null){
                     parent = cur;
                }
                stack.push(cur);
                cur = cur.left;
            } else {
                cur = stack.pop();
                if (parent.left == cur && cur.left == null && cur.right == null) {
                    sum += cur.val;
                }
                cur = cur.right;
            }
        }
        return sum;
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s