-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathIterativePostorder.java
63 lines (61 loc) · 1.7 KB
/
IterativePostorder.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
import java.util.*;
public class IterativePostorder
{
public static void main(String[] args) {
BinaryTreeNode ROOT = null;
BinaryTreeNode a = new BinaryTreeNode(1);
BinaryTreeNode b = new BinaryTreeNode(2);
BinaryTreeNode c = new BinaryTreeNode(3);
BinaryTreeNode d = new BinaryTreeNode(4);
BinaryTreeNode e = new BinaryTreeNode(5);
BinaryTreeNode f = new BinaryTreeNode(6);
BinaryTreeNode g = new BinaryTreeNode(7);
ROOT=a;
ROOT.setLeft(b);
ROOT.setRight(c);
b.setLeft(d);
b.setRight(e);
c.setLeft(f);
c.setRight(g);
postorder(ROOT);
}
public static void postorder(BinaryTreeNode ROOT)
{
if(ROOT==null)
{
return;
}
Stack<BinaryTreeNode> S = new Stack<BinaryTreeNode>();
S.push(ROOT);
BinaryTreeNode prev=null;
while(!S.isEmpty())
{
BinaryTreeNode current = S.peek();
if(prev==null || prev.left==current || prev.right==current)
{
//traverse left then right
if(current.left!=null)
{
S.push(current.left);
}
else if(current.right!=null)
{
S.push(current.right);
}
}
else if(current.left==prev)
{
if(current.right!=null)
{
S.push(current.right);
}
}
else
{
System.out.print(current.data+" ");
S.pop();
}
prev=current;
}
}
}