大致思路:二叉树前序遍历(深度优先遍历)用tmp记录遍历的数据的和,深度+1,tmp*10。若当前节点左右子树都为null,将tmp加到res中。当这个节点遍历完成,将tmp/10。
public class Solution {
int tmp = 0;
int res = 0;
public int sumNumbers (TreeNode root) {
// write code here
dfs(root);
return res;
}
void dfs(TreeNode root){
if(root==null){
return;
}
tmp=tmp*10+root.val;
dfs(root.left);
dfs(root.right);
if(root.left==null&&root.right==null) res+=tmp;
tmp = tmp/10;
}
}