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,null,null,15,7]
,
return its bottom-up level order traversal as:
1 2 3 4 5
| [ [15,7], [9,20], [3] ]
|
思路
102题也是一道层次遍历的题。在102题中,题目要求是采用自顶向下的输出方式;而这一题采用了自底向上的输出方式。
由于两道题思路相同,都是在队列访问的时候加入空节点用于分割,就不再赘述了。代码后面附上参考链接。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
| class Solution(object): def levelOrderBottom(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ q = [] res = [] layer = [] if (root): q.append(root) q.append(None) else: return q while (len(q) > 0): node = q[0] layer.append(q[0]) del q[0] if (node is not None): if (node.left is not None): q.append(node.left) if (node.right is not None): q.append(node.right) else: layerval = [] if(len(q) > 0): q.append(None) for i in layer: if (i): layerval.append(i.val) res.append(layerval) layer = [] lastlayer = [] for i in layer: if (i): lastlayer.append(i.val) res.append(lastlayer) res.reverse() return res
|
参考链接:http://www.cnblogs.com/miloyip/archive/2010/05/12/binary_tree_traversal.html