leetcode107. 二叉树的层次遍历 II

简单题,下班之前闲着没事水了一道,方法也不优雅

主要思路就是记录每层节点数,配合队列que去实现

class Solution(object):
    def levelOrderBottom(self, root):
        """
        :type root: TreeNode
        :rtype: List[List[int]]
        """
        if root is None:
            return []
        else:
            result = []
            que = [root]
            num = 1
            while num != 0:
                tmp = []
                new_num = num
                num = 0
                for i in range(new_num):
                    node = que.pop(0)
                    tmp.append(node.val)
                    if node.left:
                        que.append(node.left)
                        num += 1
                    if node.right:
                        que.append(node.right)
                        num += 1
                result.insert(0, tmp)
            return result

 

你可能感兴趣的:(LeetCode,数据结构,算法)