您的位置:首页 > 编程语言 > Python开发

python剑指offer系列把二叉树打印成多行

2018-03-02 15:12 507 查看
题目:
从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。

思路:

按层遍历,遍历完每层后更新

solution:# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None

class Solution:
def Print(self, pRoot):
if not pRoot:
return []
nodeStack = [pRoot]
result = []
while nodeStack:
res = []
nextStack = []
for i in nodeStack:
res.append(i.val)
if i.left:
nextStack.append(i.left)
if i.right:
nextStack.append(i.right)
nodeStack = nextStack
result.append(res)
return result

# write code here
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: