Leetcode-199题:Binary Tree Right

2016-09-26  本文已影响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
上一篇 下一篇

猜你喜欢

热点阅读