Given a binary tree, return the bottom-up level traversal of its node values. (That is, from the layer where the leaf node is located to the layer where the root node is located, traversing layer by layer from left to right)
For example:
given a binary tree [3,9,20,null,null,15,7]
,
3 / \ 9 20 / \ 15 7
Return its bottom-up level traversal as:
[ [15,7], [9,20], [3] ]
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def levelOrderBottom(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ if root == None: return [] temp=[] res=[] stack=[] n=1 stack.append(root) while stack: #stack is used to traverse all elements of the tree, temp stores the elements of each layer, n judges whether the elements of this layer are processed node=stack.pop(0) n-=1 temp+=[node.val] if node.left!=None: stack.append(node.left) if node.right!=None: stack.append(node.right) if n == 0: res.insert(0,temp) temp=[] n = len (stack) return res