LeetCode 129. 【Java】129. Sum Root to Leaf Numbers
原题链接
中等
作者:
tt2767
,
2020-04-12 15:34:25
,
所有人可见
,
阅读 606
/**
1. 深搜不断累加路径上的值, 当累加到叶子节点时, 合并结果
2. 搜索顺序: 不断累加路径上的值
3. 搜索状态: cur, prev_value | result
4. 剪枝: cur == null 跳出
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int sumNumbers(TreeNode root) {
int[] result = new int[1];
dfs(root, 0, result);
return result[0];
}
public void dfs(TreeNode cur, int prev, int[] result){
if (cur == null) return;
int value = prev * 10 + cur.val;
if (cur.left == null && cur.right == null) result[0] += value;
dfs(cur.left, value, result);
dfs(cur.right, value, result);
}
}