Binary Tree Leaf Sum
题目:
Given a binary tree, calculate the sum of leaves.
分析:
简单题,bfs,15分钟
解法:
public class Solution {
/**
* @param root the root of the binary tree
* @return an integer
*/
public int leafSum(TreeNode root) {
// Write your code
int res = 0;
if (root == null) {
return res;
}
Queue<TreeNode> myQueue = new LinkedList<TreeNode>();
myQueue.offer(root);
while(!myQueue.isEmpty() ) {
int size = myQueue.size();
for (int i = 0; i < size; i++) {
TreeNode temp = myQueue.poll();
if (temp.left == null && temp.right == null) {
res += temp.val;
continue;
}
if (temp.left != null) {
myQueue.offer(temp.left);
}
if (temp.right != null) {
myQueue.offer(temp.right);
}
}
}
return res;
}
}