Skip to content

Instantly share code, notes, and snippets.

@junjiah
Last active September 10, 2015 18:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save junjiah/1e25db519c6c2dbc012b to your computer and use it in GitHub Desktop.
Save junjiah/1e25db519c6c2dbc012b to your computer and use it in GitHub Desktop.
solved 'Binary Tree Right Side View' on LeetCode https://leetcode.com/problems/binary-tree-right-side-view/
# 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 []
q, right_side = collections.deque([root]), []
rightmost_node = root
while q:
top_node = q.popleft()
if top_node.left:
q.append(top_node.left)
if top_node.right:
q.append(top_node.right)
if top_node == rightmost_node:
right_side.append(top_node.val)
rightmost_node = q[-1] if q else None
return right_side
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment