-
Notifications
You must be signed in to change notification settings - Fork 1k
/
Copy pathpreOrderTraversal.java
87 lines (86 loc) · 2.36 KB
/
preOrderTraversal.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
import java.util.*;
import java.util.Stack;
class Node {
Node left;
Node right;
int data;
Node(int data) {
this.data = data;
left = null;
right = null;
}
}
class preOrderTraversal{
//recursive
public static void preOrderRec(Node root){
if(root == null)
return;
else{
System.out.print(root.data+" ");
preOrderRec(root.left);
preOrderRec(root.right);
}
}
//iterative
public static void preOrderIte(Node root) {
if (root == null) {
return;
}
Stack<Node> stack = new Stack<>();
stack.push(root);
while (!stack.empty()) {
Node node = stack.pop();
if (node != null) {
System.out.print(node.data + " ");
stack.push(node.right);
stack.push(node.left);
}
}
}
public static Node insert(Node root, int data) {
if(root == null) {
return new Node(data);
} else {
Node curr;
if(data <= root.data) {
curr = insert(root.left, data);
root.left = curr;
} else {
curr = insert(root.right, data);
root.right = curr;
}
return root;
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter number of nodes:");
int t = sc.nextInt();
System.out.println("Enter nodes:");
Node root = null;
while(t-- > 0) {
int data = sc.nextInt();
root = insert(root, data);
}
System.out.print("Recursive approach: ");
preOrderRec(root);
System.out.println();
System.out.print("Iterative approach: ");
preOrderIte(root);
sc.close();
}
}
/*
sample Input Input:
1 Enter no of nodes : 6
\ Enter nodes : 1 2 5 3 6 4
2
\ output:
5 1 2 5 3 4 6
/ \
3 6
\
4
Sample Output
1 2 5 3 4 6
*/