LeetCode刷题实战129:求根到叶子节点数字之和
Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.
An example is the root-to-leaf path 1->2->3 which represents the number 123.
Find the total sum of all root-to-leaf numbers.
Note: A leaf is a node with no children.
题意
解题
class Solution {
public int sumNumbers(TreeNode root) {
if(root==null) {
return 0;
}else {
return getNumber(root,root.val);
}
}
public int getNumber(TreeNode root,int number) {
if(root.left==null&&root.right==null) {
return number;
}
int templeft=0;
int tempright=0;
if(root.left!=null) {
templeft=getNumber(root.left,root.left.val+number*10);
}
if(root.right!=null) {
tempright=getNumber(root.right,root.right.val+number*10);
}
return templeft+tempright;
}
}