LeetCode-199、二叉树的右视图-中等
给定一棵二叉树,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。
示例:
输入: [1,2,3,null,5,null,4]
输出: [1, 3, 4]
解释:
1 <---
/ \
2 3 <---
\ \
5 4 <---
代码:
# 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]:
ans = []
if not root:
return ans
stack = [root]
while stack:
ans.append(stack[-1].val)
tmp = []
for node in stack:
if node.left:
tmp.append(node.left)
if node.right:
tmp.append(node.right)
stack = tmp
return ans