-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuestion257.java
More file actions
77 lines (67 loc) · 2.18 KB
/
Copy pathQuestion257.java
File metadata and controls
77 lines (67 loc) · 2.18 KB
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import java.util.*;
public class Question257
{
public static void getPath(TreeNode root,List<String> result,List<String> finalResult)
{
String temp = result.get(0);
String temp2 = result.get(0);
temp = temp + root.val;
System.out.println("-------------");
System.out.println("Node value : "+ root.val);
System.out.println("TEmp value : "+ temp);
System.out.println("-------------");
//If leaf node return
if(root.left == null && root.right == null)
{
finalResult.add(temp);
return;
}
if(root.left != null || root.right != null)
{
temp = temp + "->";
result.clear();
result.add(temp);
//Move left
if(root.left!=null)
{
getPath(root.left,result,finalResult);
}
//Move right
if(root.right != null)
{
getPath(root.right,result,finalResult);
}
result.clear();
result.add(temp2);
}
}
public static List<String> binaryTreePaths(TreeNode root)
{
List<String> result = new ArrayList<>();
List<String> finalResult = new ArrayList<>();
if(root==null)
return result;
result.add("");
getPath(root,result,finalResult);
return finalResult;
}
public static void main(String[] args)
{
TreeNode root = new TreeNode(10,null,null);
TreeNode l1 = new TreeNode(7,null,null);
TreeNode r1 = new TreeNode(12,null,null);
TreeNode ll2 = new TreeNode(-3,null,null);
TreeNode rr2 = new TreeNode(20,null,null);
TreeNode last = new TreeNode(33,null,null);
TreeNode lastnew = new TreeNode(123,null,null);
root.left = l1;
root.right = r1;
l1.left = ll2;
r1.right = rr2;
rr2.right = last;
last.right = lastnew;
Trees.display(root);
List<String> result = binaryTreePaths(root);
System.out.println(result);
}
}