129.求根节点到叶节点数字之和
/**
* 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 sumNumbers(TreeNode root) {
if(root == null){
return 0;
}
Queue<TreeNode> queNode = new LinkedList<TreeNode>();
Queue<Integer> queVal = new LinkedList<Integer>();
int ans = 0;
queNode.offer(root);
queVal.offer(root.val);
while(!queNode.isEmpty()){
TreeNode now = queNode.poll();
int tmp = queVal.poll();
if(now.left == null && now.right == null){
ans += tmp;
}
if(now.left!=null){
queNode.offer(now.left);
queVal.offer(tmp * 10 + now.left.val);
}
if(now.right!=null){
queNode.offer(now.right);
queVal.offer(tmp * 10 + now.right.val);
}
}
return ans;
}
}