-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path39. TreeBoundaryTraversal.java
84 lines (70 loc) · 1.74 KB
/
39. TreeBoundaryTraversal.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
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
78
79
80
81
82
83
84
// User function Template for Java
/*
class Node
{
int data;
Node left, right;
public Node(int d)
{
data = d;
left = right = null;
}
}
*/
class Solution {
ArrayList<Integer> boundaryTraversal(Node node) {
// code here
ArrayList<Integer> ans = new ArrayList<>();
if(node == null)return null;
if(!leaf(node)){
ans.add(node.data);
}
left(node, ans);
addleaves(node, ans);
right(node, ans);
return ans;
}
public static boolean leaf(Node node){
return (node.left == null && node.right == null);
}
void left(Node root, ArrayList<Integer> ans){
Node curr = root.left;
while(curr != null){
if(!leaf(curr)){
ans.add(curr.data);
}
if(curr.left !=null){
curr = curr.left;
}else{
curr = curr.right;
}
}
}
void right(Node root,ArrayList<Integer> ans){
Node curr = root.right;
Stack<Integer> st = new Stack<>();
while(curr != null){
if(!leaf(curr)){
st.push(curr.data);
}
if(curr.right != null){
curr = curr.right;
}else{
curr = curr.left;
}
}
while(!st.isEmpty()){
ans.add(st.pop());
}
}
void addleaves(Node root, ArrayList<Integer> ans){
if(root == null)return;
if(leaf(root)){
ans.add(root.data);
}
else{
addleaves(root.left, ans);
addleaves(root.right, ans);
}
}
}