【LeetCode】面试题32-2. 从上到下打印二叉树II

题目:

思路:

因为要求每层节点打印到一行,所以层次遍历时需要知道行的信息。个人思路通过两个队列的转换表示换行,优化思路记录当前层队列的长度。

代码:

Python

# 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 levelOrder(self, root):
        """
        :type root: TreeNode
        :rtype: List[List[int]]
        """
        if root is None:
            return []
        levelQueue = []
        tmpQueue = [root]
        res = []
        while tmpQueue:
            # 给tmpQueue/tmpRes重新赋值[], 没有修改其元素不用deepcopy
            levelQueue = tmpQueue
            tmpQueue = []
            tmpRes = []
            for elem in levelQueue:
                tmpRes.append(elem.val)
                if elem.left is not None:
                    tmpQueue.append(elem.left)
                if elem.right is not None:
                    tmpQueue.append(elem.right)
            res.append(tmpRes)
        return res
# 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 levelOrder(self, root):
        """
        :type root: TreeNode
        :rtype: List[List[int]]
        """
        if root is None:
            return []
        queue = [root]
        res = []
        while queue:
            tmp = []
            for _ in range(len(queue)): # 这里len(queue)只在第一次计算, 之后不会变
                node = queue.pop()
                tmp.append(node.val)
                if node.left:
                    queue.insert(0, node.left)
                if node.right:
                    queue.insert(0, node.right)
            res.append(tmp)
        return res

相关问题

posted @ 2020-06-09 15:48  一只背影  阅读(115)  评论(0编辑  收藏  举报