初學python,須要實現一個決策樹,首先實踐一下利用python實現一個二叉樹數據結構。建樹的時候作了處理,保證創建的二叉樹是平衡二叉樹。
node
# -*- 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 def get_val(self): return self.val def set_val(self,val): self.val=val def get_left(self): return self.left def set_left(self,left): self.left=left def get_right(self): return self.right def set_right(self,right): self.right=right class Tree: def __init__(self,list): list=sorted(list) self.root=self.build_tree(list) #遞歸創建平衡二叉樹 def build_tree(self,list): l=0 r=len(list)-1 if(l>r): return None if(l==r): return Node(list[l]) mid=(l+r)/2 root=Node(list[mid]) root.left=self.build_tree(list[:mid]) root.right=self.build_tree(list[mid+1:]) return root #前序遍歷 def preorder(self,root): if(root is None): return print root.val self.preorder(root.left) self.preorder(root.right) #後序遍歷 def postorder(self,root): if(root is None): return self.postorder(root.left) self.postorder(root.right) print root.val #中序遍歷 def inorder(self,root): if(root is None): return self.inorder(root.left) print root.val self.inorder(root.right) #層序遍歷 def levelorder(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 not None: queue.append(node.left) if node.right is not None: queue.append(node.right) 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)
輸出:python
中序遍歷
-1
1
3
4
5
層序遍歷
3
-1
4
1
5
前序遍歷
3
-1
1
4
5
後序遍歷
1
-1
5
4
3數據結構
創建的二叉樹以下圖所示:app