python實現二叉樹

2022-05-26 14:54:11 字數 2413 閱讀 2814

初學python,需要實現乙個決策樹,首先實踐一下利用python實現乙個二叉樹資料結構。建樹的時候做了處理,保證建立的二叉樹是平衡二叉樹。

#

-*- coding: utf-8 -*-

from collections import

deque

class

node:

def__init__(self,val,left=none,right=none):

self.val=val

self.left=left

self.right=right

#setter and getter

defget_val(self):

return

self.val

defset_val(self,val):

self.val=val

defget_left(self):

return

self.left

defset_left(self,left):

self.left=left

defget_right(self):

return

self.right

defset_right(self,right):

self.right=right

class

tree:

def__init__

(self,list):

list=sorted(list)

self.root

=self.build_tree(list)

#遞迴建立平衡二叉樹

defbuild_tree(self,list):

l=0r=len(list)-1

if(l>r):

return

none

if(l==r):

return

node(list[l])

mid=(l+r)/2root=node(list[mid])

root.left=self.build_tree(list[:mid])

root.right=self.build_tree(list[mid+1:])

return

root

#前序遍歷

defpreorder(self,root):

if(root is

none):

return

print

root.val

self.preorder(root.left)

self.preorder(root.right)

#後序遍歷

defpostorder(self,root):

if(root is

none):

return

self.postorder(root.left)

self.postorder(root.right)

print

root.val

#中序遍歷

definorder(self,root):

if(root is

none):

return

self.inorder(root.left)

print

root.val

self.inorder(root.right)

#層序遍歷

deflevelorder(self,root):

if root is

none:

return

queue =deque([root])

while(len(queue)>0):

size=len(queue)

for i in

range(size):

node =queue.popleft()

print

node.val

if node.left is

notnone:

if node.right is

notnone:

list=[1,-1,3,4,5]

tree=tree(list)

print

'中序遍歷:

'tree.inorder(tree.root)

print

'層序遍歷:

'tree.levelorder(tree.root)

print

'前序遍歷:

'tree.preorder(tree.root)

print

'後序遍歷:

'tree.postorder(tree.root)

輸出:中序遍歷-11

345層序遍歷3-1

415前序遍歷3-1

145後序遍歷1-1

543建立的二叉樹如下圖所示:

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實現平衡二叉樹 平衡二叉樹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實現二叉樹翻轉

題 給定一棵二叉樹,要求輸出其左右翻轉後二叉樹的中序遍歷。例 翻轉前 翻轉後 1 1 2 3 3 2 4 5 5 4思路 映象翻 只需要遍歷二叉樹,每次訪問乙個結點時,交換其左右孩子,然後遞迴的翻轉左右孩子。class node object def init self,val none lchil...