概述
class TreeNode:
def __init__(self,val):
super(TreeNode).__init__()
self.val = val
self.left = None
self.right = None
self.isPop = False
def createTree(valList):
if not valList:
raise ValueError("input value list is None!")
root = TreeNode(valList[0])
valList.pop(0)
layerOne = [root]
layerTwo = []
i = 0
while i<len(valList):
n = layerOne.pop(0)
if valList[i] is not None:
n.left = TreeNode(valList[i])
layerOne.append(n.left)
i = i+1
if i<len(valList) and valList[i] is not None:
n.right = TreeNode(valList[i])
layerOne.append(n.right)
i = i+1
return root
valList = [1,2,3,4,None,6,7,8,9,None,11,12,13]
root = createTree(valList)
def inOrder(root):
stack = []
p = root
while stack or p:
if p:
stack.append(p)
p = p.left
else:
p = stack.pop()
print(p.val,end = " ")
p = p.right
print()
def preOrder(root):
if not root:
return
stack = [root]
while stack:
p = stack.pop()
print(p.val,end=" ")
if p.right:
stack.append(p.right)
if p.left:
stack.append(p.left)
print()
def postOrder(root):
def operate(node,stack):
if node.left is None and node.right is None or node.isPop:
print(node.val,end=" ")
else:
stack.append(node)
if node.right:
stack.append(node.right)
if node.left:
stack.append(node.left)
return stack
if not root:
return
stack = [root]
while stack:
p = stack.pop()
stack=operate(p,stack)
p.isPop = True
preOrder(root) #1 2 4 8 9 3 6 11 7 12 13
inOrder(root) #8 4 9 2 1 6 11 3 12 7 13
postOrder(root) #8 9 4 2 11 6 12 13 7 3 1
后序遍历的实现方法中,改变节点的入栈顺序也可以用来实现另外两种遍历
最后
以上就是高兴咖啡豆为你收集整理的leetcode: 二叉树的三种非递归遍历的全部内容,希望文章能够帮你解决leetcode: 二叉树的三种非递归遍历所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复