-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathIterativeInOrder.java
97 lines (89 loc) · 2.39 KB
/
IterativeInOrder.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
85
86
87
88
89
90
91
92
93
94
95
96
97
/*https://practice.geeksforgeeks.org/problems/inorder-traversal-iterative/0/*/
//modification approach
class Tree
{
ArrayList<Integer> inOrder(Node root)
{
Stack<Node> stack = new Stack<Node>();
ArrayList<Integer> list = new ArrayList<Integer>();
if (root == null)
return list;
stack.push(root);
while (!stack.isEmpty())
{
Node temp = stack.peek();
if (temp.left != null && temp.left.data > 0)
stack.push(temp.left);
else
{
Node curr = stack.pop();
list.add(curr.data);
curr.data *= -1;
if (curr.right != null && curr.right.data > 0)
stack.push(curr.right);
}
}
return list;
}
}
//pointer approach
class Tree
{
ArrayList<Integer> inOrder(Node root)
{
ArrayList<Integer> list = new ArrayList<Integer>();
Stack<Node> stack =new Stack<Node>();
if (root == null)
return list;
Node curr = root;
while (curr != null || !stack.isEmpty())
{
//if pointer is not null
if (curr != null)
{
//push into stack and go left
stack.push(curr);
curr = curr.left;
}
else //otherwise
{
//pop from stack and add to list
curr = stack.pop();
list.add(curr.data);
//go right
curr = curr.right;
}
}
return list;
}
}
//best approach
class Solution {
ArrayList<Integer> list;
public int[] solve(Tree root) {
if (root == null) return new int[0];
list = new ArrayList<Integer>();
Stack<Tree> stack = new Stack<Tree>();
Tree curr = root;
while (curr != null)
{
stack.push(curr);
curr = curr.left;
}
while (!stack.isEmpty())
{
curr = stack.pop();
list.add (curr.val);
curr = curr.right;
while (curr != null)
{
stack.push(curr);
curr = curr.left;
}
}
int[] result = new int[list.size()];
for (int i = 0; i < result.length; ++i)
result[i] = (Integer)list.get(i);
return result;
}
}