原题链接在这里:https://leetcode.com/problems/binary-tree-paths/
DFS 依次添加,终止条件是叶子节点。
Note: 1. 如果使用StringBuilder, 在递归调用时,必须写成new StringBuilder(sb). 否则会报错.
e.g. [1,2,3], 会写成["1->2","1->23"]. 因为扫过点2,StringBuilder 会变成1->2, 扫过点3,原来的点2没有去掉,就会变成1->23,但是第一个结果没有变成1->23是因为,用到sb.toString()时自动做了copy by value.
2 . 但如果使用String,在递归调用时可以直接使用str, 因为String 和 int, float一样是priority type, 是copy by value,而不像array等object式copy by reference.
3. 在使用String时,前面要写String str = new String(), 等号右面的初始化不可以省略。
AC Java:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> res = new ArrayList<String>();
if(root == null){
return res;
}
dfs(root, new StringBuilder(), res);
return res;
}
private void dfs(TreeNode root, StringBuilder sb, List<String> res){
if(root.left == null && root.right == null){
sb.append(root.val);
res.add(sb.toString());
return;
}
sb.append(root.val);
sb.append("->");
if(root.left != null){
dfs(root.left,new StringBuilder(sb),res);
}
if(root.right != null){
dfs(root.right,new StringBuilder(sb),res);
}
}
}
上面使用StringBuilder, 下面使用String.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> res = new ArrayList<String>();
if(root == null){
return res;
}
String str = new String();
dfs(root, str, res);
return res;
}
private void dfs(TreeNode root, String str, List<String> res){
if(root.left == null && root.right == null){
str = str + String.valueOf(root.val);
res.add(str);
return;
}
str += String.valueOf(root.val);
str += "->";
if(root.left != null){
dfs(root.left,str,res);
}
if(root.right != null){
dfs(root.right,str,res);
}
}
}