题目链接
BFS + 队列
/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode() {}* TreeNode(int val) { this.val = val; }* TreeNode(int val, TreeNode left, TreeNode right) {* this.val = val;* this.left = left;* this.right = right;* }* }*/
class Solution {public int sumOfLeftLeaves(TreeNode root) {int sum = 0;Deque<TreeNode> queue = new LinkedList<TreeNode>();if(root == null){return sum;}queue.offer(root);while(!queue.isEmpty()){int size = queue.size();for(int i = 0; i < size; i++){TreeNode node = queue.poll();if(node.left != null){queue.offer(node.left);// 注意题目要求是求左叶子之和,所以需要判断一下左节点是否为叶子节点if(node.left.left == null && node.left.right == null){sum += node.left.val;}}if(node.right != null){queue.offer(node.right);}}}return sum;}
}