1 class Solution: 2 def __init__(self): 3 self.list = [] 4 self.result = [] 5 6 def levelOrder(self,level): 7 count = len(level) 8 while count > 0: 9 root = level.pop(0) 10 self.list.append(root.val) 11 if root.left != None: 12 level.append(root.left) 13 if root.right != None: 14 level.append(root.right) 15 count -= 1 16 if len(self.list) > 0: 17 self.result.append(self.list[:]) 18 self.list = [] 19 if len(level) > 0: 20 self.levelOrder(level) 21 22 def rightSideView(self, root: TreeNode) -> List[int]: 23 if root == None: 24 return self.list 25 else: 26 level = [] 27 level.append(root) 28 self.levelOrder(level) 29 res = [] 30 for li in self.result: 31 res.append(li[-1]) 32 return res
二叉树层次遍历,最后返回每一层的最后一个节点组成的集合。