forked from terrytong0876/LintCode-1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinary Tree Right Side View.java
executable file
·131 lines (104 loc) · 2.99 KB
/
Binary Tree Right Side View.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
M
最右:即level traversal每一行的最末尾.
BFS,用queue.size()来出发saving result.
```
/*
Given a binary tree, imagine yourself standing on the right side of it,
return the values of the nodes you can see ordered from top to bottom.
For example:
Given the following binary tree,
1 <---
/ \\
2 3 <---
\\ \\
5 4 <---
You should return [1, 3, 4].
Tags: Tree, Depth-first Search, Breadth-first Search
Similar Problems: (M) Populating Next Right Pointers in Each Node
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
/*
02.09.2016 Revist
Thoughts:
BFS: traverse all levels, save to ArrayList, get all nodes at end of level list.
*/
public class Solution {
public List<Integer> rightSideView(TreeNode root) {
List<Integer> rst = new ArrayList<Integer>();
if (root == null) {
return rst;
}
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.offer(root);
int size = queue.size();
while (!queue.isEmpty()) {
TreeNode node = queue.poll();
size--;
if (node.left != null) {
queue.offer(node.left);
}
if (node.right != null) {
queue.offer(node.right);
}
if (size == 0) {
rst.add(node.val);
size = queue.size();
}
}
return rst;
}
}
/*
自己想了这个方法,有可能不是特别efficient.
一个queue放普通的BFS。
一个queue放level。
同时维护一个parent value;维护一个跟着BFS跑的level。
每个node都有一个lv。一旦lv和正在跑的level不一样,证明lv>level,那么也就是说,刚刚换行拉。parent的值,就是上一行最右边的值。DONE.
Thoughts:
Use 2 queue: one for BFS, one for level. Each node in queue has a corresponding level
Track level.
WHen level != levelQ.poll(), that means we are moving to next level, and we should record the previous(parent) node's value.
*/
public class Solution {
public List<Integer> rightSideView(TreeNode root) {
List<Integer> rst = new ArrayList<Integer>();
if (root == null) {
return rst;
}
Queue<TreeNode> q = new LinkedList<TreeNode>();
Queue<Integer> levelQ = new LinkedList<Integer>();
q.offer(root);
levelQ.offer(1);
int level = 1;
int parent = root.val;
TreeNode node = null;
while (!q.isEmpty()) {
node = q.poll();
int lv = levelQ.poll();
if (level != lv) {
level++;
rst.add(parent);
}
parent = node.val;
if (node.left != null) {
q.offer(node.left);
levelQ.offer(lv + 1);
}
if (node.right != null) {
q.offer(node.right);
levelQ.offer(lv + 1);
}
}//END while
rst.add(parent);
return rst;
}
}
```