面试36题:面试
题:二叉搜索树与双向链表app
题目:输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能建立任何新的结点,只能调整树中结点指针的指向。spa
解题思路一:因为输入的一个二叉搜索树,其左子树大于右子树的值,这位后面的排序作了准备,由于只须要中序遍历便可,将全部的节点保存到一个列表,。对这个list[:-1]进行遍历,每一个节点的right设为下一个节点,下一个节点的left设为上一个节点。指针
借助了一个O(n)的辅助空间 code
解题代码:(注意:attr列表中的元素是链表节点)blog
# -*- coding:utf-8 -*- # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None 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)
解题思路二:递归,将特定节点的左指针指向其左子树中的最后子节点,将其右指针指向其右子树中的最左子节点,依次递归,调整好所有节点的指针指向。排序
解题代码:递归
# -*- coding:utf-8 -*- # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None 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