1 / \ 2 3 \ 5
["1->2->5", "1->3"]
题意:
给出一个二叉树,返回所有根节点到叶子的路径
public class LeetCode257 {
public List<String> binaryTreePaths(TreeNode root) {
List<String> path = new ArrayList<>();
if(root == null) return path;
String onepath = "";
paths(root, onepath, path);
return path;
}
public static void paths(TreeNode root, String curPath, List<String> path){
curPath = curPath + root.val ;
if(root.left == null && root.right == null){ // 到达叶子节点
path.add(curPath);
}
curPath = curPath + "->";
if(root.left != null){
paths(root.left, curPath, path);
}
if(root.right != null){
paths(root.right, curPath, path);
}
}
}
129. Sum Root to Leaf Numbers
题意:
找到所有根到叶子的数字和
例如:
1 / \ 2 3
1->2 代表12
1->3 代表13
所有根到叶子的和为:12+13=25
解题思路:
思路1:和上题类似,先求出所有路径,推进一步乘以10,求出所有数字,然后相加。
思路2:递归相加
public class LeetCode129 {
/*
public int sumNumbers(TreeNode root) {
List<Integer> path = new ArrayList<>();
int res = 0;
if(root == null) return res;
paths(root, 0, path);
for(Integer tmp:path){
res = res + tmp;
System.out.println(tmp);
}
return res;
}
public static void paths(TreeNode root, int curPath, List<Integer> path){
curPath = curPath + root.val ;
if(root.left == null && root.right == null){
path.add(curPath);
}
curPath = curPath * 10;
if(root.left != null){
paths(root.left, curPath, path);
}
if(root.right != null){
paths(root.right, curPath, path);
}
}
*/
public int sumNumbers(TreeNode root) {
return dfs(root, 0);
}
public int dfs(TreeNode root, int sum) {
if(root == null) return 0;
if(root.left == null && root.right == null) return root.val + sum * 10;
return dfs(root.left, root.val + sum * 10) + dfs(root.right, root.val + sum * 10);
}
}