面試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