-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPrintLeftViewIterative1
70 lines (61 loc) · 1.46 KB
/
PrintLeftViewIterative1
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
//using in-order traversal
import java.util.Stack; //Time Complexity: O(n)
/* Class containing left and right child of current
node and key value*/
class Node
{
int data;
Node left, right;
public Node(int item)
{
data = item;
left = right = null;
}
}
/* Class to print the left view */
class BinaryTree
{
static Node root;
// recursive function to print left view
void leftViewUtil(Node node)
{
// Base Case
if (node==null) return;
//keep the nodes in the path that are waiting to be visited
Stack<Node> stack = new Stack<Node>();
//first node to be visited will be the left one
while (node != null) {
System.out.print(node.data + " ");
stack.push(node);
node = node.left;
}
// traverse the tree
while (stack.size() > 0) {
// visit the top node
node = stack.pop();
if (node.right != null) {
node = node.right;
// the next node to be visited is the leftmost
while (node != null) {
stack.push(node);
node = node.left;
if(node!=null){
System.out.print(node.data + " ");
}
}
}
}
}
/* testing for example nodes */
public static void main(String args[])
{
/* creating a binary tree and entering the nodes */
BinaryTree tree = new BinaryTree();
tree.root = new Node(12);
tree.root.left = new Node(10);
tree.root.right = new Node(30);
tree.root.right.left = new Node(25);
tree.root.right.right = new Node(40);
tree.leftViewUtil(root);
}
}