问题
例子
思路
-
方法1
先序遍历:sb回溯,
-
方法2
先序遍历:不用回溯
代码
//方法1
class Solution {
private int res=0;
public int sumNumbers(TreeNode root) {
if(root==null) return 0;
backtrack(root, new StringBuilder());
return res;
}
public void backtrack(TreeNode root, StringBuilder sb,) {
if(root==null) return ;
sb.append(root.val);
if(root.left==null && root.right==null)
res+=Integer.valueOf(sb.toString());
else{
if(root.left!=null) backtrack(root.left,sb);
if(root.right!=null) backtrack(root.right,sb);
}
sb.delete(sb.length()-1,sb.length());
}
}
//方法2
class Solution {
private int res=0;
public int sumNumbers(TreeNode root) {
if(root==null) return 0;
preOrder(root, 0);
return res;
}
public void preOrder(TreeNode root, int val) {
if(root==null) return ;
int k = val*10+root.val;
if(root.left==null && root.right==null)
{
res+=k;
return;
}
if(root.left!=null) preOrder(root.left,k);
if(root.right!=null) preOrder(root.right,k);
}
}