剑指offer_二叉树_把二叉树打印成多行

把二叉树打印成多行

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

解题思路
此题与另外一道题很相似,解题思路也十分相似,参考答案可见这里
参考代码

# -*- 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
        result = []
        if not pRoot:
            return result
        currnodes = [pRoot]
        while currnodes:
            currvalues = []
            nextnodes = []
            for node in currnodes:
                currvalues.append(node.val)
                if node.left:
                    nextnodes.append(node.left)
                if node.right:
                    nextnodes.append(node.right)
            result.append(currvalues[:])
            currnodes = nextnodes
        return result 
发布了31 篇原创文章 · 获赞 0 · 访问量 712

猜你喜欢

转载自blog.csdn.net/freedomUSTB/article/details/105180596