129. 求根节点到叶节点数字之和
小于 1 分钟
129. 求根节点到叶节点数字之和中等
解法:dfs
class Solution {
int res = 0;
public int sumNumbers(TreeNode root) {
dfs(root, 0);
return res;
}
public void dfs(TreeNode node, int sum) {
sum = sum * 10 + node.val;
if (node.left == null && node.right == null) {
res += sum;
} else if (node.left == null) {
dfs(node.right, sum);
} else if (node.right == null) {
dfs(node.left, sum);
} else {
dfs(node.right, sum);
dfs(node.left, sum);
}
}
}
Powered by Waline v2.15.5