class
binarysearchtree
(object)
:
def __init__
(self,key)
:
self.key=key
self.left=none
self.right=none
def find
(self,x)
:if x==self.key:
return self
elif xreturn self.left.
find
(x)
elif x>self.key and self.right:
return self.right.
find
(x)else
:return none
def findmin
(self)
:if self.left:
return self.left.
findmin()
else
:return self
def insert
(self,x)
:if xif self.left:
self.left.
insert
(x)else
:
tree=
binarysearchtree
(x)
self.left=tree
elif x>self.key:
if self.right:
self.right.
insert
(x)else
:
tree=
binarysearchtree
(x)
self.right=tree
def delete
(self,x)
:if self.
find
(x):
if xself.left=self.left.
delete
(x)return self
elif x>self.key:
self.right=self.right.
delete
(x)return self
elif self.left and self.right:
key=self.right.
findmin()
.key
self.key=key
self.right=self.right.
delete
(key)
return self
else
:if self.left:
return self.left
else
:return self.right
else
:return self
題目描述
輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。例如輸入前序遍歷序列和中序遍歷序列,則重建二叉樹並返回。
#class
treenode
:# def __init__
(self, x)
:# self.val = x
# self.left = none
# self.right = none
class
solution
: # 返回構造的treenode根節點
def reconstructbinarytree
(self, pre, tin)
: # write code here
if not pre or not tin:
return none
root=
treenode
(pre[0]
) #rootval=pre[0]
p = self.
find
(pre[0]
,tin)
if p!=none:
root.left = self.
reconstructbinarytree
(pre[
1:p+1]
,tin[
0:p]
) root.right = self.
reconstructbinarytree
(pre[p+1:
],tin[p+1:
])return root
def find
(self,val,tin)
:for j in
range
(len
(tin)):
if tin[j]
==val:
return j
return none
先序遍歷:根左右
中序遍歷:左根右
後序遍歷:左右根
程式設計題練習日記 2 二叉樹遍歷
前序中序後序,按層次。這裡遞迴的很好寫就不寫了,主要複習非遞迴的。樹 4 2 6 1 3 5 7 810 非遞迴前序 unrecursive preorder,非遞迴前序遍歷 preorder binarytreeroot if s.empty 非遞迴前序遍歷 4 2 1 3 6 5 7 8 10 ...
python 二叉樹查詢 Python二叉樹搜尋
stack depth is initialised to 0 def find in tree node,find condition,stack depth assert stack depth max stack depth deeper than max depth stack depth ...
python二叉數排序
在物件導向中 物件不能包含物件 用 引用來控制物件 排序 二叉數 class btree root none 根class node 建立了3個盒子 data none left none right none 核心 def zhongxu self if self.left is not none...