1.dfs
/**
* 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;
}
int[] res = new int[1];
dfs(root, root.val, res);
return res[0];
}
public void dfs(TreeNode root, int temp, int[] res) {
//1.终止条件
if (root.left == null && root.right == null) {
res[0] += temp;
return;
}
//2.遍历节点
if (root.left != null) {
dfs(root.left, temp * 10 + root.left.val, res);
}
if (root.right != null) {
dfs(root.right, temp * 10 + root.right.val, res);
}
}
}