-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinaryTreeRightSideView.py
More file actions
38 lines (36 loc) · 983 Bytes
/
binaryTreeRightSideView.py
File metadata and controls
38 lines (36 loc) · 983 Bytes
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
# 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].
# 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]
"""
if not root: return []
st = [(root, 0)]
res = []
while(st):
n, l = st.pop()
if len(res) < l + 1:
res += [n.val]
else:
res[l] = n.val
if n.right: st += [(n.right, l + 1)]
if n.left: st += [(n.left, l + 1)]
return res