二叉树转化为双向链表

在这里插入代码
class Solution:
	def __init__(self):
		#指定两个节点 listHead为始终不变的头结点
		#listTail为变化的节点
		self.listHead = None
		self.listTail = None

	def Convert(self, pRootOfTree):
		if pRootOfTree == None:
			return
		self.Convert(pRootOfTree.left)
		
		if self.listHead == None:
			#第一次初始化两个节点
			self.listHead = pRootOfTree
			self.listTail = pRootOfTree
		else:
			#将变化的节点右子节点连接到上一节点
			#将上一节点的左子树连接到变化的及诶点
			self.listTail.right = pRootOfTree
			pRootOfTree.left = self.listTail
			#将变化的节点上移到上一节点
			self.listTail = pRootOfTree
		self.Convert(pRootOfTree.right)
		return self.listHead

	def printList(self, head):
		while head.right:
			print(head.val, end = " ")
			head = head.right
		print(head.val)
		while head:
			print(head.val, end = " ")
			head = head.left
	def getBSTwithPreTin(self, pre, tin):
		if len(pre) == 0 | len(tin) == 0:
			return None
		root = TreeNode(pre[0])
		for order, item in enumerate(tin):
			if root.val == item:
				root.left = self.getBSTwithPreTin(pre[1:order+1], tin[:order]) #213, 123 //
				root.right = self.getBSTwithPreTin(pre[order+1:], tin[order+1:]) #657, 567 //
				return root

class TreeNode:
	def __init__(self, x):
		self.left = None
		self.right = None
		self.val = x

if __name__ == '__main__':
	solution = Solution()
	preorder_seq = [4, 2, 1, 3, 6, 5, 7]
	middleorder_seq = [1, 2, 3, 4, 5, 6, 7]
	treeRoot1 = solution.getBSTwithPreTin(preorder_seq, middleorder_seq)
	head = solution.Convert(treeRoot1)
	solution.printList(head)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值