1. 程式人生 > >【劍指offer】二叉搜尋樹與雙向連線

【劍指offer】二叉搜尋樹與雙向連線

題目描述
輸入一棵二叉搜尋樹,將該二叉搜尋樹轉換成一個排序的雙向連結串列。要求不能建立任何新的結點,只能調整樹中結點指標的指向。
普通的二叉樹也可以轉換成雙向連結串列,只不過不是排序的


思路:

  1. 與中序遍歷相同
  2. 採用遞迴,先連結左指標,再連結右指標

程式碼1,更改doubleLinkedList,最後返回list的第一個元素:

class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right =
None class Solution: def lastElem(self, list): if len(list) == 0: return None else: return list[len(list) - 1] def ConvertCore(self, pRoot, doubleLinkedList): if pRoot: if pRoot.left: self.ConvertCore(pRoot.left, doubleLinkedList)
pRoot.left = self.lastElem(doubleLinkedList) if self.lastElem(doubleLinkedList): self.lastElem(doubleLinkedList).right = pRoot doubleLinkedList.append(pRoot) if pRoot.right: self.ConvertCore(pRoot.right, doubleLinkedList)
def Convert(self, pRootOfTree): if pRootOfTree == None: return None doubleLinkedList = [] self.ConvertCore(pRootOfTree, doubleLinkedList) return doubleLinkedList[0]

程式碼2,lastListNode指向雙向連結串列中的最後一個節點,因此每次操作最後一個節點。這裡要更改值,因此採用list的形式。

class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None
class Solution:
    def ConvertCore(self, pRoot, lastListNode):
        if pRoot:
            if pRoot.left:
                self.ConvertCore(pRoot.left, lastListNode)
            pRoot.left = lastListNode[0]
            if lastListNode[0]:
                lastListNode[0].right = pRoot
            lastListNode[0] = pRoot
            if pRoot.right:
                self.ConvertCore(pRoot.right, lastListNode)
    def Convert(self, pRootOfTree):
        # write code here
        if pRootOfTree == None:
            return None
        lastListNode = [None]
        self.ConvertCore(pRootOfTree, lastListNode)
        while lastListNode[0].left:
            lastListNode[0] = lastListNode[0].left
        return lastListNode[0]