Given a binary tree, return all root-to-leaf paths.
Note: A leaf is a node with no children.
Example:
Input:
1
/ \
2 3
\
5
Output: [“1->2->5”, “1->3”]
Explanation: All root-to-leaf paths are: 1->2->5, 1->3
思路:
DFS,对于路径的保存用String,而不是StringBuilder,因为StringBuilder是引用参数,在Parent节点的路径到了child节点做了修改再跳出来的时候,StringBuilder的内容无法回到之前保存的路径
如下面的例子 (验证String与StringBuilder,与此题无关):
public static void main(String[] args){
String tmpS = "1";
StringBuilder tmpB = new StringBuilder();
tmpB.append(1);
addString(tmpS);
addBuilder(tmpB);
System.out.println("tmpS = " + tmpS);
System.out.println("tmpB = " + tmpB);
}
public static void addString(String tmp) {
tmp += "2";
System.out.println("tmpS inside = " + tmp);
}
public static void addBuilder(StringBuilder tmp1) {
tmp1.append("2");
}
output:
tmpS inside = 12
tmpS = 1
tmpB = 12
可见String在其他函数做修改跳出后不变,而StringBuilder的值发生了改变
DFS:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> result = new ArrayList<>();
String tmp = "";
dfs(result, tmp, root);
return result;
}
public void dfs(List<String> result, String tmp, TreeNode root) {
if (root == null) {
return;
}
tmp += root.val;
if (root.left == null && root.right == null) {
result.add(tmp);
return;
} else {
tmp += "->";
}
dfs(result, tmp, root.left);
dfs(result, tmp, root.right);
}
}