代码拉取完成,页面将自动刷新
# Time: O(n)
# Space: O(h)
#
# 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:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# @param root, a tree node
# @return a list of integers
def rightSideView(self, root):
result = []
self.rightSideViewDFS(root, 1, result)
return result
def rightSideViewDFS(self, node, depth, result):
if not node:
return
if depth > len(result):
result.append(node.val)
self.rightSideViewDFS(node.right, depth+1, result)
self.rightSideViewDFS(node.left, depth+1, result)
# BFS solution
# Time: O(n)
# Space: O(n)
class Solution2:
# @param root, a tree node
# @return a list of integers
def rightSideView(self, root):
if root is None:
return []
result, current = [], [root]
while current:
next_level = []
for i, node in enumerate(current):
if node.left:
next_level.append(node.left)
if node.right:
next_level.append(node.right)
if i == len(current) - 1:
result.append(node.val)
current = next_level
return result
if __name__ == "__main__":
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.right = TreeNode(5)
root.right.right = TreeNode(4)
result = Solution().rightSideView(root)
print result
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。