-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeft_view.java
More file actions
70 lines (57 loc) · 1.41 KB
/
Left_view.java
File metadata and controls
70 lines (57 loc) · 1.41 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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
// Java program to print left view of Binary
// Tree
import java.util.*;
public class Left_view {
// Binary tree node
private static class Node {
int data;
Node left, right;
public Node(int data)
{
this.data = data;
this.left = null;
this.right = null;
}
}
// function to print left view of binary tree
private static void printLeftView(Node root)
{
if (root == null)
return;
Queue<Node> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()) {
// number of nodes at current level
int n = queue.size();
// Traverse all nodes of current level
for (int i = 0; i < n; i++) {
Node temp = queue.poll();
// Print the left most element at
// the level
if (i == 0)
System.out.print(temp.data + " ");
// Add left node to queue
if (temp.left != null)
queue.add(temp.left);
// Add right node to queue
if (temp.right != null)
queue.add(temp.right);
}
}
}
// Driver code
public static void main(String[] args)
{
// construct binary tree as shown in
// above diagram
Node root = new Node(10);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(7);
root.left.right = new Node(8);
root.right.right = new Node(15);
root.right.left = new Node(12);
root.right.right.left = new Node(14);
printLeftView(root);
}
}