代码改变世界

[LeetCode] 199. Binary Tree Right Side View_ Medium tag: BFS, Amazon

2018-07-04 04:04  Johnson_强生仔仔  阅读(192)  评论(0编辑  收藏  举报

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       <---

 这个题目也是经典的BFS, 依次scan tree的每一层, 然后将第一个看到的元素append进入ans里面即可. 这里思路是根据ans的size来判断该层是否已经append过了, 如果append过了那么就继续测试他的children. 最后返回ans.

 

1. Constraints

  1) Tree 可以为empty, 但是因为返回的是array, 所以可以将edge case放到queue里面去判断即可.

 

2. Ideas

   BFS     T: O(n),  S: O(n)   n is number of nodes of the tree

  1) ans(init: []), queue( init: [root, 0])

  2) while queue:  node, heig = queue.popleft(), 根据len(ans), 和heig的大小来判断该层是否被append过, 如果没有, 那么append进入ans

  3) 先判断right children, 因为是right view, 那么同理如果出一个题目, 问的是left view, 那么code基本不变, 只是将判断right children 和left children的顺序换下即可.

  4) return ans

3. code

 1 class Solution:
 2     def rightSideView(self, root):
 3         ans, queue = [], collections.deque([(root, 0)])
 4         while queue:
 5             node, heig = queue.popleft()
 6             if node:
 7                 if heig == len(ans):
 8                     ans.append(node.val)
 9                 if node.right:
10                     queue.append((node.right, heig + 1))
11                 if node.left:
12                     queue.append((node.left, heig + 1))
13         return ans

 

similar, if we change the question into Binary Tree Left Side View. then the code is similar, but change the order to append left and right child.

 1 class Solution:
 2     def leftSideView(self, root):
 3         ans, queue = [], collections.deque([(root, 0)])
 4         while queue:
 5             node, heig = queue.popleft()
 6             if node:
 7                 if heig == len(ans):
 8                     ans.append(node.val)
 9                 if node.left:
10                     queue.append((node.left, heig + 1))
11                 if node.right:
12                     queue.append((node.right, heig + 1))
13         return ans

 

 

 

4. Test cases

1) empty tree

2) 

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

3)

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