https://leetcode.com/problems/sum-of-left-leaves/description/
计算给定二叉树的所有左叶子之和。
示例:
在这个二叉树中,有两个左叶子,分别是 9 和 15,所以返回 24
3
/ \
9 20
/ \
15 7
解题思路:
层序遍历,当一个节点的左节点存在,并且该左节点为叶子节点,则将它的值累加。
/**
* 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) {
Queue<TreeNode> queue = new LinkedList<TreeNode>();
int sum = 0;
if(root==null)return 0;
queue.offer(root);
while(!queue.isEmpty()){
TreeNode node = queue.poll();
if(node.left!=null&&node.left.left==null&&node.left.right==null){
sum+=node.left.val;
}
if(node.left!=null)queue.offer(node.left);
if(node.right!=null)queue.offer(node.right);
}
return sum;
}
}