题解 | #把二叉树打印成多行#

把二叉树打印成多行

http://www.nowcoder.com/practice/445c44d982d04483b04a54f298796288

# -*- 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 None
        result=[]
        level_tmp=[]
        level=[]
        queue=[]
        queue.append(pRoot)
        level.append(0)
        i=0
        while len(queue)>0:
            node=queue[0]
            queue.pop(0)
            if i==level[0]:
                level_tmp.append(node.val)
                level.pop(0)
            elif i!=level[0]:
                result.append(level_tmp)
                level_tmp=[]
                level_tmp.append(node.val)
                i=level[0]
                level.pop(0)

            if node.left!=None:
                queue.append(node.left)
                level.append(i+1)
            if node.right!=None:
                queue.append(node.right)
                level.append(i+1)
        result.append(level_tmp)
        return result

全部评论

相关推荐

点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务