二叉树和链表——Python实现
本文基于LeetCode36:二叉搜索树与双向链表问题扩展而来
题目链接:LeetCode
题目描述:输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的循环双向链表。要求不能创建任何新的节点,只能调整树中节点指针的指向。
实现功能包括:
1、由列表生成二叉树
2、二叉树的前序、中序、后序遍历
3、借助中序遍历思想实现二叉树转双向链表
class Node:
def __init__(self, val, left = None, right = None):
self.val = val
self.left = left
self.right = right
class NodeOperation:
def createBinaryTree(self,list):
return self.iterationTree(list)
def iterationTree(self, list): #使用递归实现二叉树的创建
if len(list) == 1:
return Node(list[0])
node = Node(list[0])
i = 1
while i<len(list) and list[i]<list[0]:
i += 1
node.left = self.iterationTree(list[1:i])
node.right = self.iterationTree(list[i:])
return node
def pre_Oder(self,root): #先序遍历
if root == None:
return
print(root.val, end=" ")
self.pre_Oder(root.left)
self.pre_Oder(root.right)
return
def mid_Oder(self,root): #中序遍历
if root == None:
return
self.mid_Oder(root.left)
print(root.val,end=" ")
self.mid_Oder(root.right)
def las_Oder(self,root): #后序遍历
if root == None:
return
self.las_Oder(root.left)
self.las_Oder(root.right)
print(root.val, end=" ")
def tree2DoublyList(self,root): #二叉树转双向链表
pre = None
head = None
def iteration(root): #定义一个用于递归的内部函数
if root == None:
return
iteration(root.left)
nonlocal pre #这里相当于设置了一个全局指针,用于标记已经遍历节点的最后一个节点位置,也可以采用类变量的方式生成指针
nonlocal head #用于标记头节点位置
if pre == None:
head = root
else:
pre.right = root
root.left = pre
pre = root
iteration(root.right)
return
iteration(root)
if head == None:
return None
head.left = pre
pre.right = head
return head
def printDoublyList(self,root): #验证双向链表的生成
point = root
while point!=root.left:
print(point.val,end=" ")
point = point.right
print(point.val)
if __name__ == "__main__":
l = [4,2,1,3,6,5,7]
Nod = NodeOperation()
root = Nod.createBinaryTree(l)
print("输出先序遍历:")
Nod.pre_Oder(root)
print("\n","输出中序遍历:")
Nod.mid_Oder(root)
print("\n","输出后续遍历:")
Nod.las_Oder(root)
head = Nod.tree2DoublyList(root)
Nod.printDoublyList(head)
输出结果
输出先序遍历:
4 2 1 3 6 5 7
输出中序遍历:
1 2 3 4 5 6 7
输出后续遍历:
1 3 2 5 7 6 4 1 2 3 4 5 6 7