Geek

博客园 首页 新随笔 联系 订阅 管理

 

 

/**
 * 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 on 2020-07-15 20:16  .geek  阅读(113)  评论(0编辑  收藏  举报