-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSideViewOfBinaryTree.java
91 lines (77 loc) · 2.95 KB
/
SideViewOfBinaryTree.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
88
89
90
91
package com.anudev.ds.trees;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
public class SideViewOfBinaryTree {
// to get the left side view do the level order traversal and then
// take the first element from the level order traversal
public static void printLeftSideView(Node node) {
System.out.print("Left side view: ");
ArrayList<Node> leftSideViewList = new ArrayList<>();
Queue<Node> queue = new LinkedList<>();
// for end at each level we are going to add null to it.
queue.add(node);
leftSideViewList.add(queue.peek());
queue.add(null);
while (!queue.isEmpty()) {
Node queueNode = queue.poll();
if (queueNode == null) {
// if the queue is empty just exit
// if queue is not empty just put the first item after
// item is found null in the queue.
if (queue.isEmpty()) {
break;
} else {
leftSideViewList.add(queue.peek());
}
queue.add(null);
} else {
if (queueNode.getLeftNode() != null) {
queue.add(queueNode.getLeftNode());
}
if (queueNode.getRightNode() != null) {
queue.add(queueNode.getRightNode());
}
}
}
for (Node nodeData : leftSideViewList) {
System.out.print(nodeData.getValue() + ",");
}
}
// to get the right side view do the level order traversal and then
// take the last element from the level order traversal
public static void printRightSideView(Node node) {
System.out.println();
System.out.print("Right side view: ");
Node lastNode = null;
ArrayList<Node> rightSideViewList = new ArrayList<>();
Queue<Node> queue = new LinkedList<>();
// for end at each level we are going to add null to it.
queue.add(node);
queue.add(null);
while (!queue.isEmpty()) {
Node queueNode = queue.poll();
if (queueNode == null) {
// if the queue is empty just exit
// if queue is not empty just put the first item after
// item is found null in the queue.
rightSideViewList.add(lastNode);
if (queue.isEmpty()) {
break;
}
queue.add(null);
} else {
if (queueNode.getLeftNode() != null) {
queue.add(queueNode.getLeftNode());
}
if (queueNode.getRightNode() != null) {
queue.add(queueNode.getRightNode());
}
lastNode = queueNode;
}
}
for (Node nodeData : rightSideViewList) {
System.out.print(nodeData.getValue() + ",");
}
}
}