題目描述
輸入一棵二叉搜尋樹,將該二叉搜尋樹轉換成乙個排序的雙向鍊錶。要求不能建立任何新的結點,只能調整樹中結點指標的指向。
普通的二叉樹也可以轉換成雙向鍊錶,只不過不是排序的
思路: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 selwww.cppcns.comf.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, do程式設計客棧ublelinkedlist)
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 = lastlistnomxvkjfozlpde[0]
if lastlistnode[0]:
lastlistnode[0].right = proot
lastlistnode[0] = proot
if proot.
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]
二叉搜尋樹與雙向鍊錶 Python
鍊錶定義 鍊錶是一種遞迴的資料結構,它或者為空 null 或者是指向乙個結點 node 的引用,該節點還有乙個元素和乙個指向另一條鍊錶的引用。鍊錶是一種線性表,但它不像順序表那樣連續儲存元素,而是在每乙個節點裡存到下乙個節點的指標 pointer 由於不用連續儲存,插入的時間複雜度為o 1 比順序表...
二叉搜尋樹與雙向鍊錶
1.問題描述 輸入一顆二叉搜尋樹,將該二叉搜尋樹轉換成乙個排序的雙向鍊錶。要求不能建立任何新的結點,只能調整樹中結點指標的指向。來自 劍指offer 2.分析 對於二叉搜尋樹我們知道,樹的左孩子都比根節點要下,樹的右孩子都比根結點要大,根據這個特點,我們進行中序遍歷得到的序列就會滿足題目的要求,我們...
二叉搜尋樹與雙向鍊錶
問題描述 輸入一棵二叉搜尋樹,將該二叉搜尋樹轉換成乙個排序的雙向鍊錶。要求不能建立任何新的結點,只能調整樹中結點指標的指向。演算法 struct binarytreenode binarytreenode convert binarytreenode prootoftree plastnodeinl...