剑指Offer(Python多种思路实现):二叉搜索树与双向链表
面试36题:
题:二叉搜索树与双向链表
题目:输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
解题思路一:由于输入的一个二叉搜索树,其左子树大于右子树的值,这位后面的排序做了准备,因为只需要中序遍历即可,将所有的节点保存到一个列表,。对这个list[:-1]进行遍历,每个节点的right设为下一个节点,下一个节点的left设为上一个节点。借助了一个O(n)的辅助空间
class Solution:
def Convert(self, pRootOfTree):
# write code here
if not pRootOfTree:
return
self.attr=[]
self.inOrder(pRootOfTree)
for i,v in enumerate(self.attr[:-1]):
self.attr[i].right=self.attr[i+1]
self.attr[i+1].left=v
return self.attr[0]
def inOrder(self,root):
if not root:
return
self.inOrder(root.left)
self.attr.append(root)
self.inOrder(root.right)
解题思路二:递归,将特定节点的左指针指向其左子树中的最后子节点,将其右指针指向其右子树中的最左子节点,依次递归,调整好全部节点的指针指向。
class Solution:
def Convert(self, pRootOfTree):
# write code here
if not pRootOfTree:
return
root=pHead=pRootOfTree
while pHead.left:
pHead=pHead.left
self.Core(root)
return pHead
def Core(self,root):
if not root.left and not root.right:
return
if root.left:
preRoot=root.left
self.Core(root.left)
while preRoot.right:
preRoot=preRoot.right
preRoot.right=root
root.left=preRoot
if root.right:
nextRoot=root.right
self.Core(root.right)
while nextRoot.left:
nextRoot=nextRoot.left
nextRoot.left=root
root.right=nextRoot