[LeetCode]129. 求根节点到叶节点数字之和(java实现)
1. 题目
2. 读题(需要重点注意的东西)
思路(dfs):
爆搜,用path记录每一条路径的数,当遍历到叶子节点时,加path加到res结果中即可。
3. 解法
---------------------------------------------------解法---------------------------------------------------
/**
* 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 {
int res = 0;
public int sumNumbers(TreeNode root) {
dfs(root,0);
return res;
}
public void dfs(TreeNode root,int path){
path = path*10 + root.val;
if(root.left == null && root.right == null){
res += path;
return;
}
if(root.left != null) dfs(root.left,path);
if(root.right != null) dfs(root.right,path);
}
}
可能存在的问题: