bonfy / algorithm-in-5-minutes

Algorithm in 5 minutes
0 stars 0 forks source link

7. Binary Tree Right Side View #7

Open bonfy opened 5 years ago

bonfy commented 5 years ago

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

Leetcode: 199. Binary Tree Right Side View - https://leetcode.com/problems/binary-tree-right-side-view/

bonfy commented 5 years ago

解法: BFS

O(N) N 为 node 数

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def rightSideView(self, root: TreeNode) -> List[int]:
        if not root:
            return []

        tmp = [[root]]
        mid = [[root.val]]

        while tmp:
            tt = []
            cur = tmp.pop()
            for i in cur:
                if i.left:
                    tt.append(i.left)
                if i.right:
                    tt.append(i.right)
            if tt:
                tmp.append(tt)
                mid.append([i.val for i in tt])
        ans = [i[-1] for i in mid]
        return ans