Title

#树#遍历#leetCode404.左子树之和

 

 

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int sumOfLeftLeaves(TreeNode root) {
        if(root == null) return 0;
        Deque<Result> q = new LinkedList<>();
        q.push(new Result(root,false));
        int sum = 0;
        while(q.isEmpty()==false) {
            Result result = q.poll();
            TreeNode parent = result.node;
            if(result.isLeft && parent.left==null && parent.right==null) {
                sum += parent.val;
            }
            if(parent.left!=null) {
                q.offer(new Result(parent.left,true));
            }
            if(parent.right!=null) {
                q.offer(new Result(parent.right,false));
            }
        }
        return sum;
    }

     
    class Result {
        TreeNode node;
        boolean  isLeft;
        Result(TreeNode n,boolean a) {
            node = n;
            isLeft = a;
        }
    }
}

 

posted @ 2020-07-15 20:16  .geek  阅读(112)  评论(0编辑  收藏  举报