力扣 中等 129.求根节点到叶子结点数字之和
文章目录
- 题目介绍
- 解法
题目介绍
解法
法一:有返回值、
class Solution {public int sumNumbers(TreeNode root) {return dfs(root, 0);}public int dfs(TreeNode root, int x) {if (root == null) {return 0;}x = x * 10 + root.val;if (root.left == root.right) { // root 是叶子节点return x;}return dfs(root.left, x) + dfs(root.right, x);}
}
法二:无返回值
class Solution {int ans = 0;public int sumNumbers(TreeNode root) {dfs(root,0);return ans;}public void dfs(TreeNode node, int x) {if (node == null) {return;}x = x * 10 + node.val;if (node.left == node.right) { // node 是叶子节点ans += x;return;}dfs(node.left, x);dfs(node.right, x);}
}