Leetcode-199题:Binary Tree Right Side View

题目:Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.

For example:
Given the following binary tree,

1 <---
/   
2  3 <---
 \   
 5   4 <---

You should return [1, 3, 4].

思路:其实就是按层次遍历,保留每层的最右边的结点

代码:

def rightSideView(self, root):
    """
    :type root: TreeNode
    :rtype: List[int]
    """
    result = []
    if root == None:
        return result
    queue = [root,'#']
    tag = True
    while len(queue) != 1:
        node = queue[0]
        queue.remove(node)
        if node == '#':
            tag = True
            queue.append('#')
        else:
            if node.right != None:
                queue.append(node.right)
            if node.left != None:
                queue.append(node.left)
            if tag:
                result.append(node.val)
                tag = False
    return result
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 目录 简书的 markdown 都不支持 [TOC] 语法……我就不贴目录了。下面按照类别,列出了29道关于二叉树...
    被称为L的男人阅读 3,383评论 0 8
  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,779评论 0 33
  • 要是有一天要死,我绝不像个傻子一样喃喃重复说我爱你,也不要犯傻去问你有没有爱过我。我一句话都不会留。你要知道我想说...
    谁家窗明月昨阅读 243评论 0 0
  • 就在刚才,我翻完了《我就想浅浅地教语文》。暑假开始到现在,这是我读完第一遍的第二本书,囫囵吞枣般地读完了。如果要我...
    山鬼_碧芳阅读 234评论 0 1
  • 2017.0501321:14 打开App 公司:淮北慕思寝具。 226 期 苏州 感谢一组学员 ...
    慕思寝具阅读 204评论 0 0