码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode 199 Binary Tree Right Side View

时间:2016-04-14 16:03:45      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:

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].

BFS 每层都以从右向左的顺序扔数组里取出第一个到结果数组中,然后再对下一层同样操作。

class Solution(object):
    def rightSideView(self, root):
        if not root:
            return []
        a, ans = [root], []
        while a:
            b = []
            ans.append(a[0].val)
            for node in a:
                if node.right:
                    b.append(node.right)
                if node.left:
                    b.append(node.left)
            a = b
        return ans

Leetcode 199 Binary Tree Right Side View

标签:

原文地址:http://www.cnblogs.com/lilixu/p/5391245.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!