LeetCode_Binary Tree Right Side View

Binary Tree Right Side View

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.
(二叉树的右视图)

Example:



1. BFS按层遍历

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
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None

class Solution:
def rightSideView(self, root: TreeNode) -> List[int]:
if not root:
return []

result = []
stack = [root]
while stack:
result.append(stack[0].val)
new_stack = []
for node in stack:
if node.right:
new_stack.append(node.right)
if node.left:
new_stack.append(node.left)
stack = new_stack

return result