leetcood学习笔记-107-二叉树的层次遍历二

题目描述:

方法一:

class Solution(object):
    def levelOrderBottom(self, root):
        """
        :type root: TreeNode
        :rtype: List[List[int]]
        """
        if not root:
            return []
        ans = []
        stack = [root]
        while stack:
            tmp_stack = []
            tmp_ans = []
            for i in stack:
                tmp_ans.append(i.val)
                if i.left:
                    tmp_stack.append(i.left)
                if i.right:
                    tmp_stack.append(i.right)
            stack = tmp_stack
            ans.append(tmp_ans)
            
        return ans[::-1]

 递归:

class Solution:
    def levelOrderBottom(self, root: TreeNode) -> List[List[int]]:
        res = []
        def helper(root, depth):
            if not root: return 
            if depth == len(res):
                res.insert(0, [])
            res[-(depth+1)].append(root.val)
            helper(root.left, depth+1)
            helper(root.right, depth+1)
        helper(root, 0)
        return res

 

posted @ 2019-03-21 21:38  oldby  阅读(110)  评论(0编辑  收藏  举报