Last active
September 10, 2015 18:20
-
-
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/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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