404. Sum of Left Leaves

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

思路: 套用tree traversal的模板,用in-order traversal来做,需要加个parent节点来跟踪,用来判断何时做和

 

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
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