题目:
从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
思路:
按层遍历,遍历完每层后更新
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
本文介绍了一种按层遍历二叉树的方法,并详细解释了如何实现每一层节点从左至右输出的功能。通过使用栈来跟踪节点,该算法能够有效地处理二叉树结构并逐层展示其数据。

被折叠的 条评论
为什么被折叠?



