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

107. Binary Tree Level Order Traversal II

时间:2016-06-19 01:22:03      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:

题目:

Given a binary tree, return the bottom-up level order traversal of its nodes‘ values. (ie, from left to right, level by level from leaf to root).

For example:
Given binary tree {3,9,20,#,#,15,7},

    3
   /   9  20
    /     15   7

 

return its bottom-up level order traversal as:

[
  [15,7],
  [9,20],
  [3]
]

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.

链接: http://leetcode.com/problems/binary-tree-level-order-traversal-ii/

一刷,比102题只多了最后一步,还是用了2个list,第二遍可以试一下DFS

 1 class Solution(object):
 2     def levelOrderBottom(self, root):
 3         if not root:
 4             return []
 5         result = []
 6         prev = [root]
 7         cur = []
 8         
 9         while prev:
10             for elem in prev:
11                 if elem.left:
12                     cur.append(elem.left)
13                 if elem.right:
14                     cur.append(elem.right)
15             result.append([e.val for e in prev])
16             prev, cur = cur, []
17         result.reverse()
18         return result

 

107. Binary Tree Level Order Traversal II

标签:

原文地址:http://www.cnblogs.com/panini/p/5597287.html

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