二叉树前序、中序、后序遍历,递归和非递归实现
程序员文章站
2022-05-16 14:54:04
...
class TreeNode:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
class Order:
def __init__(self):
self.result = []
def preOrder(self, node):
if not node:
return
self.result.append(node.data)
self.preOrder(node.left)
self.preOrder(node.right)
def preOrder2(self, node):
nodeList = []
while nodeList or node:
if node:
self.result.append(node.data)
nodeList.append(node)
node = node.left
else:
node = nodeList.pop()
node = node.right
def midOrder(self, node):
if not node:
return
self.midOrder(node.left)
self.result.append(node.data)
self.midOrder(node.right)
def midOrder2(self, node):
nodeList = []
while nodeList or node:
if node:
nodeList.append(node)
node = node.left
else:
node = nodeList.pop()
self.result.append(node.data)
node = node.right
def posOrder(self, node):
if not node:
return
self.posOrder(node.left)
self.posOrder(node.right)
self.result.append(node.data)
def posOrder2(self, node):
nodeList = []
while nodeList or node:
if node:
nodeList.append(node)
node = node.left
else:
node = nodeList[-1]
if not node.right:
self.result.append(node.data)
nodePop = nodeList.pop()
nodeNow = nodeList[-1]
# 出栈的是左子树节点,跳到右子树
if nodeNow.left == nodePop:
node = nodeNow.right
# 出栈的是右子树节点时,双亲节点出栈
elif nodeNow.right == nodePop:
self.result.append(nodeNow.data)
nodeList.pop()
if nodeList:
node = nodeList[-1].right
else:
node = None
else:
node = node.right
nodeList.append(node)
if __name__ == '__main__':
A = TreeNode(1)
B = TreeNode(2)
C = TreeNode(3)
D = TreeNode(4)
E = TreeNode(5)
F = TreeNode(6)
A.left = B
A.right = C
B.left = D
B.right = E
C.left = F
ss = Order()
ss.posOrder(A)
print(ss.result)
推荐阅读
-
Python实现输入二叉树的先序和中序遍历,再输出后序遍历操作示例
-
PHP实现二叉树深度优先遍历(前序、中序、后序)和广度优先遍历(层次)实例详解
-
[PHP] 算法-根据前序和中序遍历结果重建二叉树的PHP实现
-
Python实现二叉树前序、中序、后序及层次遍历示例代码
-
【算法】二叉树的前序、中序、后序、层序遍历和还原。
-
PHP基于非递归算法实现先序、中序及后序遍历二叉树操作示例
-
数据结构---树的前、中、后序遍历非递归实现
-
剑指 Offer 07. 重建二叉树——【前中序】和【中后序】重建二叉树的递归思路详解
-
C二叉树前序遍历中序遍历后续遍历递归非递归
-
二叉树遍历 前序遍历 后序遍历 中序遍历 非递归前序遍历 二叉树遍历非递归