剑指offer:把二叉树打印成多行

题目描述

从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。

用队列来实现按行打印,但是由于要分层打印,需要区分每一行,所以要用一个tmp来记录每层打印出的结果

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    # 返回二维列表[[1,2],[4,5]]
    def Print(self, pRoot):
        # write code here
        if pRoot==None:
            return []
        q=[pRoot]
        res=[]
        while q!=[]:
            tmp=[]
            qtmp=[]
            for i in q:
                tmp.append(i.val)
                if i.left:
                    qtmp.append(i.left)
                if i.right:
                    qtmp.append(i.right)
            q=qtmp
            res.append(tmp)
        return res

上面的情况空间复杂度较高,因为不仅有一个tmp来记录每一层的值,还有一个qtmp来记录每一层的节点。下面这种方法用low和high两个索引来记录,low从队列0索引,high记录的是队列未递归到下一层时的队列长度。例如第一层high是1,虽然根节点append了两个孩子,队列长度变长了,但是high没有变,还是记录的根节点1的长度。等到第二次外层循环的时候high变为2

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    # 返回二维列表[[1,2],[4,5]]
    def Print(self, pRoot):
        # write code here
        if pRoot==None:
            return []
        q=[pRoot]
        result=[]
        tmp=[]
        while q!=[]:
            low=0
            high=len(q)
            while low<high:
                low+=1
                t=q.pop(0)
                tmp.append(t.val)
                if t.left:
                    q.append(t.left)
                if t.right:
                    q.append(t.right)
            result.append(tmp)
            tmp=[]
        return result

猜你喜欢

转载自blog.csdn.net/gt362ll/article/details/82915293