搜尋二叉樹的python實現

2021-07-15 12:59:54 字數 3296 閱讀 2237

我的**片:

'''

功能:在二叉搜尋樹中查詢乙個元素,若該元素存在則返回該元素,否則返回該元素若存在時的父母結點

引數:key:結點的鍵值

root:二叉樹的根節點

'''def

find

(key, root):

# 若該樹為空樹或者根節點的鍵值等於key,則返回根節點

if root == none

or root.key == key:

return root

# 若該樹非空,且key不等於根節點的鍵值,則先判讀key值對應的結點在root的左子樹還是右子樹

# 若key小於root的鍵值,那麼key值對應的結點在root的左子樹

if root.key > key:

# 若root的左子樹存在,遞迴查詢

if root.left != none:

return find(key, root.left)

# 若root的左子樹不存在,key對應的結點不存在,返回root

return root

# 若key大於root的鍵值,在root的右子樹中查詢key對應的結點

if root.key < key:

# 若root的右子樹存在,遞迴查詢

if root.right != none:

return find(key, root)

# 否則直接返回root

return root

''' 功能:往書中插入乙個結點

引數:n

'''def

insert

(n):

# 找出n的父母節點

m = find(n)

# 若n的鍵值小於m的鍵值,則n為m的左孩子結點

if m.key >n.key:

m.left = n

n.parent = m

# 否則n為m的右孩子結點

else:

m.right = n

n.parent = m

''' 功能:返回大於鍵值key的最小結點,若key是二叉樹中最大的結點,則返回key對應的結點

引數:n:二叉樹的某一結點

'''def

next

(n):

# 如果n有右孩子樹,返回n的右孩子樹的左孩子葉子結點

m = find(max, root)

if m == n:

return n

if n.right != none:

return leftdescendant(n.right)

# 如果n沒有右孩子結點,返回n的右父母結點

if n.right == none:

return rightancenstor(n)

defleftdescendant

(n):

if n.left == none

or n == none:

return n

return leftdesendant(n.left)

defrightancenstor

(n):

if n == n.parent.left:

return n.parent

return leftancenstor(n.parent)

''' 功能:刪除輸入結點

引數:n:要刪除的結點

'''def

delete

(n):

# 若n沒有右孩子結點,n的父母結點指向n的左孩子結點

if n.right == none:

n.left.parent = n.parent

# 若n是右孩子結點

if n.parent.right == n:

n.prent.right = n.left

return

# 若n是左孩子結點

if n.parent.left == n:

n.parent.left = n.left

return

# 若n有右孩子結點

else:

# 查詢大於n的最小結點

x = next(n)

# 用x替代n

n.key = x.key

# 刪除x,由於x一定是左孩子結點

x.parent.left = none

return

''' 功能:輸出鍵值在x,y之間的一系列結點

引數:x,y,root

'''def

rangerearch

(x, y, root):

l =

n = find(x, root)

while n != false

and n.key <= y:

if n.key >= x:

n = next(x)

return l

''' 功能:將兩棵樹合成

引數:r1,r2(r1中的元素小於r2)

'''def

merge

(r1, r2):

# 在r1中找出最大的元素,作為合成樹的根節點

r = find(max, r1)

# 刪除r

delete(r)

# 合成樹

mergewithroot(r1, r2, r)

return r

defmergewithroot

(r1, r2, r):

# r1作為r的左子樹

r.left = r1

r1.parent = r

# r2作為r的右子樹

r.right = r2

r2.parent = r

return r

''' 功能:將樹r分割成兩棵樹r1和r2(r1的元素均小於x,r2的元素均大於x)

引數:樹的根節點r, 分割的鍵值

'''def

split

(x, r):

if r == none:

return (none, none)

if r.key >= x:

(r1, r2) = split(x, r.left)

r3 = mergewithroot(r2, r.right, r)

return (r1, r3)

if x > r.key:

(r1, r2) = split(x, r.right)

r3 = mergewithroot(r1, r.left, r)

return (r3, r2)

二叉樹 還原二叉樹 二叉搜尋樹

先序遍歷的特點 先遍歷根結點,再遍歷左子樹,最後再遍歷右子樹 中序遍歷的特點 先遍歷左子樹,再遍歷根結點,最後再遍歷右子樹 後序遍歷的特點 先遍歷左子樹,再遍歷右子樹,最後再遍歷根結點 舉例 先序遍歷 a b d f g h i e c 中序遍歷 f d h g i b e a c 如上,根據先序遍...

樹 二叉樹 二叉搜尋樹

給定乙個二叉樹,判斷其是否是乙個有效的二叉搜尋樹。假設乙個二叉搜尋樹具有如下特徵 節點的左子樹只包含小於當前節點的數。節點的右子樹只包含大於當前節點的數。所有左子樹和右子樹自身必須也是二叉搜尋樹。示例 1 輸入 2 13輸出 true 示例 2 輸入 5 14 3 6輸出 false 解釋 輸入為 ...

排序二叉樹or搜尋二叉樹or查詢二叉樹

排序二叉樹,搜尋二叉樹,查詢二叉樹都是乙個意思,只是叫法不同而已。下面的文章中我們統稱為排序二叉樹。本文主要是針對高中資訊學,因此其中不涉及到指標,所有需要用指標的地方都直接使用陣列進行模擬。排序二叉樹定義 1 若左子樹不空,則左子樹上所有結點的值均小於或等於它的根結點的值 2 若右子樹不空,則右子...