卖萌的弱渣

I am stupid, I am hungry.

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

Given the following binary tree,

1
2
3
4
5
6
   1            <---
 /   \
2     3         <---
 \     \
  5     4       <---
You should return [1, 3, 4].

Solution

  • Java: Recursive File /Users/minli/Desktop/Personal/sdytlm.github.io/source/downloads/code/LeetCode/Java/Binary-Tree-Right-Size-View.java could not be found

  • BFS

(Binary-Tree-Right-Side-View.py) download
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
# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def rightSideView(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """

        stack = []
        ret = []

        if root == None:
            return ret

        stack.append([root,level])

        while stack:
            top = stack.pop(0)
            node = top[0]
            cur_level = top[1]

            if node.left != None:
                stack.append([node.left,cur_level+1])
            if node.right != None:
                stack.append([node.right,cur_level+1])

            if not stack or cur_level != stack[0][1]:
                ret.append(node.val)

        return ret