迭代

通过层次遍历,拿到每层的做右边的元素就可以了

  class Solution(object):
      def rightSideView(self, root):
          """
          :type root: TreeNode
          :rtype: List[int]
          """
          if not root: return []
          cur, res  = [root], []
          while cur:
              tmp_cur = []
              tmp_res = []
              for node in cur:
                  if node.left:
                      tmp_cur.append(node.left)
                  if node.right:
                      tmp_cur.append(node.right)
                  tmp_res.append(node.val)
              res.append(tmp_res[-1])
              cur= tmp_cur
          return res