LeetCode-199 二叉树的右视图
Table of Contents
LeetCode-199 二叉树的右视图 #
Solution 1 #
层序遍历 (BFS).
代码如下:
class Solution:
def rightSideView(self, root: Optional[TreeNode]) -> List[int]:
if root is None:
return []
p1 = [root]
ans = []
while p1:
p2 = []
ans.append(p1[-1].val)
for node in p1:
if node.left:
p2.append(node.left)
if node.right:
p2.append(node.right)
p1 = p2.copy()
return ans
Solution 2 #
递归, 用深度决定是否更新到答案中.
代码如下:
class Solution:
def rightSideView(self, root: Optional[TreeNode]) -> List[int]:
ans = []
def f(root: Optional[TreeNode], d) -> None:
if root is None:
return
if d > len(ans):
ans.append(root.val)
f(root.right, d + 1)
f(root.left, d + 1)
return 0
f(root, 1)
return ans