Binary Tree Right Side View


算法:二叉树广度优先遍历 BFS

URL:https://leetcode.com/problems/binary-tree-right-side-view/

题目

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
Binary Tree Right Side View

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.

Example:
Input: [1,2,3,null,5,null,4]
Output: [1, 3, 4]
Explanation:

1 <---
/ \
2 3 <---
\ \
5 4 <---

Input: [1,2,3,null,5,null,4,null,null,8]
Output: [1, 3, 4, 8]
Explanation:

1 <---
/ \
2 3 <---
\ \
5 4 <---
/
8 <---

分析

使用层序遍历(level traversal),即广度优先搜索 —— 借助Queue

难点是 标注每一层,来标注 每层的最后一个节点

当前层节点总数:count1,当前访问到节点数 i

下一层几点总数:count2

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
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}

class Solution {
public List<Integer> rightSideView(TreeNode root) {
return BFS(root);
}
public List<Integer> BFS(TreeNode root) {
List<Integer> retList = new ArrayList<Integer>();
if(null == root) return retList;
int count1=1, count2=0;
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.add(root);
while(!queue.isEmpty()) {
for(int i=0; i<count1; ++i) {
TreeNode tn = queue.poll();
if(null != tn) {
if (i == count1-1) {
retList.add(tn.val);
}
if(null != tn.left) {
queue.add(tn.left);
count2++;
}
if (null != tn.right) {
queue.add(tn.right);
count2++;
}
}
}
count1 = count2;
count2 = 0;
}
return retList;
}
}

结果

Runtime: 1 ms, faster than 98.22% of Java online submissions for Binary Tree Right Side View.

Memory Usage: 36.3 MB, less than 100.00% of Java online submissions for Binary Tree Right Side View.

1次AC,Niubility

Python解法

1
2