剑指offer-二叉搜索树与双向链表-python
题目描述
输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。、
1 # -*- coding:utf-8 -*- 2 # class TreeNode: 3 # def __init__(self, x): 4 # self.val = x 5 # self.left = None 6 # self.right = None 7 class Solution: 8 def __init__(self): 9 self.listHead = None 10 self.listTail = None 11 def Convert(self, pRootOfTree): 12 if pRootOfTree==None: 13 return 14 #中续遍历 15 self.Convert(pRootOfTree.left) 16 if self.listHead==None: 17 self.listHead = pRootOfTree 18 self.listTail = pRootOfTree 19 else: 20 #22行与24行主要是增加双向连接 21 #22行指向listTail.right 22 self.listTail.right = pRootOfTree 23 #24行指回去 24 pRootOfTree.left = self.listTail 25 #移动到下一个位置 26 self.listTail = pRootOfTree 27 self.Convert(pRootOfTree.right) 28 return self.listHead