基本思路就是:
遍历当前层的所有根节点组成的栈,形成下一层的根节点组成的栈,outList不断叠加每一层的根节点组合的列表
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def levelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if not root:
return []
currentStack = [root]
outList= []
while currentStack:
nextStack = []
tmp = []
for point in currentStack:
if point.left:
nextStack.append(point.left)
if point.right:
nextStack.append(point.right)
tmp.append(point.val)
outList.append(tmp)
currentStack = nextStack
return outList
完整测试代码
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
'''
3
/ \
9 20
/ \
15 7
'''
class Solution(object):
def levelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if not root:
return []
currentStack = [root]
outList= []
while currentStack:
nextStack = []
tmp = []
for point in currentStack:
if point.left:
nextStack.append(point.left)
if point.right:
nextStack.append(point.right)
tmp.append(point.val)
outList.append(tmp)
currentStack = nextStack
return outList
n1 = TreeNode(3)
n2 = TreeNode(9)
n3 = TreeNode(20)
n4 = TreeNode(15)
n5 = TreeNode(7)
n1.left = n2
n1.right = n3
n3.left = n4
n3.right = n5
s = Solution()
result = s.levelOrder(n1)
print(result)
本文介绍了一种实现二叉树层次遍历的算法,通过使用栈来存储每层的节点,最后输出每一层的节点值。此算法首先将根节点放入栈中,然后不断迭代,直到栈为空。在每次迭代中,会将当前层所有节点的子节点加入到下一个栈中,同时收集当前层的节点值,最终形成层次遍历的结果。
1552

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



