-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathBT_Problem_07_a.java
More file actions
55 lines (38 loc) · 1.09 KB
/
Copy pathBT_Problem_07_a.java
File metadata and controls
55 lines (38 loc) · 1.09 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
package trees.binaryTree;
import java.util.*;
/*
* Problem Title :- Preorder Traversal of a tree without using Recursion or Iteratively
*/
public class BT_Problem_07_a {
// Root of Binary Tree
Node root;
// Given a binary tree, print its nodes in pre-order
void preorder() {
if(root == null) return;
Stack<Node> s = new Stack<>();
s.push(root);
// traverse the tree
while(s.empty() == false) {
Node mynode = s.peek();
System.out.print(mynode.data + " ");
s.pop();
//Push right child of popped node to stack
if(mynode.right != null)
s.push(mynode.right);
//Push left child of popped node to stack
if(mynode.left != null)
s.push(mynode.left);
}
}
// Driver method
public static void main(String[] args) {
// creating a binary tree and entering the nodes
BT_Problem_07_a tree = new BT_Problem_07_a();
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(5);
tree.preorder();
}
}