题目:
二叉树的右视图:给定一棵二叉树,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。
思路:
借助层序遍历来实现。
程序:
# 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 = [] current_level = [root] while current_level: auxiliary = [] next_level = [] for node in current_level: auxiliary.append(node.val) if node.left: next_level.append(node.left) if node.right: next_level.append(node.right) #result.append(auxiliary[-1]) current_level = next_level result.append(auxiliary[-1]) return result