-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbin_tree_right_view.py
More file actions
40 lines (31 loc) · 1.11 KB
/
Copy pathbin_tree_right_view.py
File metadata and controls
40 lines (31 loc) · 1.11 KB
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
# Leetcode: https://leetcode.com/problems/binary-tree-right-side-view/description/
# I've done so many of these level by level traversals that it's pretty straight forward now.
# Beats 90%, seems strange for deleting entire objects.
# 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]
"""
# Always return the right most element per level.
# Level by level traversal
if not root:
return []
queue = [(root)]
ret = []
while (len(queue) > 0):
copy = queue[:]
del queue[:]
for i in xrange(len(copy)):
if (copy[i].left):
queue.append(copy[i].left)
if (copy[i].right):
queue.append(copy[i].right)
ret.append(copy[-1].val)
return ret