forked from Jensenczx/CodeEveryday
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path11_BinaryTreePaths.java
47 lines (42 loc) · 1.1 KB
/
11_BinaryTreePaths.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import java.util.ArrayList;
import java.util.List;
class TreeNode {
public int val;
public TreeNode left, right;
public TreeNode(int val) {
this.val = val;
this.left = this.right = null;
}
}
public class Solution {
/**
* @param root the root of the binary tree
* @return all root-to-leaf paths
*/
public List<String> binaryTreePaths(TreeNode root) {
// Write your code here
List<String> list = new ArrayList<String> ();
String str = new String();
traveTree(root,str,list);
return list;
}
public void traveTree(TreeNode root,String str,List<String> list){
if(root==null)
return;
if(root.left==null&&root.right==null){
if(str.length()>0)
list.add(str+"->"+root.val);
else list.add(root.val+"");
}
else{
if(str.length()>0)
str = str+"->"+root.val;
else str = root.val+"";
String tmp = new String(str);
traveTree(root.left,str,list);
traveTree(root.right,tmp,list);
}
}
public static void main(String[]args){
}
}