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.
For example,
1 / \ 2 3
The root-to-leaf path 1->2
represents the number 12
.
The root-to-leaf path 1->3
represents the number 13
.
Return the sum = 12 + 13 = 25
.
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int sumNumbers(TreeNode root) {
return inorder(root,0);
}
public int inorder(TreeNode root,int value){//root的parent传递下来的值
if(root == null){
return 0;
}
int tmp1=0,tmp2=0,tmp3=0;//tmp1为root代表的数,tmp2为left代表的数,tmp3为right代表的数
tmp1 = value*10 + root.val;
if(root.left == null && root.right == null){//叶子节点
return tmp1;
}
//非叶子节点返回的是左右孩子节点之和
if(root.left != null){
tmp2 = inorder(root.left,tmp1);
}
if(root.right != null){
tmp3 = inorder(root.right,tmp1);
}
return tmp2+tmp3;
}
}
总体来说,这还是很简单的,一个遍历就可以实现。
Runtime: 218 ms
可能是网速快,所以运行的快,或许是leetcode计算运行时间采用的是运行时间=返回结果时间-提交时间