美文网首页
Leetcode-199题:Binary Tree Right

Leetcode-199题:Binary Tree Right

作者: 八刀一闪 | 来源:发表于2016-09-26 22:01 被阅读31次

题目: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

相关文章

网友评论

      本文标题:Leetcode-199题:Binary Tree Right

      本文链接:https://www.haomeiwen.com/subject/xtaqyttx.html