-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinaryTreePaths.java
More file actions
30 lines (29 loc) · 857 Bytes
/
BinaryTreePaths.java
File metadata and controls
30 lines (29 loc) · 857 Bytes
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
class Solution {
List<String> sol=new ArrayList<>();
public List<String> binaryTreePaths(TreeNode root) {
if(root.left==null && root.right==null){
sol.add(""+root.val);
return sol;
}
String rootval=String.valueOf(root.val);
if(root.right!=null)
paths(rootval,root.right);
if(root.left!=null)
paths(rootval,root.left);
return sol;
}
private void paths(String collective,TreeNode root){
if(root.right==null && root.left==null){
collective+="->"+root.val;
sol.add(collective);
return;
}
collective+="->"+root.val;
if(root.right!=null){
paths(collective,root.right);
}
if(root.left!=null){
paths(collective,root.left);
}
}
}