Python算法——二叉树
生活随笔
收集整理的這篇文章主要介紹了
Python算法——二叉树
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一、二叉樹
from collections import dequeclass BiTreeNode:def __init__(self, data):self.data = dataself.lchild = Noneself.rchild = Nonea = BiTreeNode('A') b = BiTreeNode('B') c = BiTreeNode('C') d = BiTreeNode('D') e = BiTreeNode('E') f = BiTreeNode('F') g = BiTreeNode('G')e.lchild = a e.rchild = g a.rchild = c c.lchild = b c.rchild = d g.rchild = froot = edef pre_order(root):if root:print(root.data, end='')pre_order(root.lchild)pre_order(root.rchild)def in_order(root):if root:in_order(root.lchild)print(root.data, end='')in_order(root.rchild)def post_order(root):if root:post_order(root.lchild)post_order(root.rchild)print(root.data, end='')def level_order(root):queue = deque()queue.append(root)while len(queue) > 0:node = queue.popleft()print(node.data,end='')if node.lchild:queue.append(node.lchild)if node.rchild:queue.append(node.rchild)pre_order(root) print("") in_order(root) print("") post_order(root) print("") level_order(root) 前序,中序,后序,層次遍歷
? ? ? ??
? ? ? ??
class BiTreeNode:def __init__(self, data):self.data = dataself.lchild = Noneself.rchild = Noneclass BST:def __init__(self, li=None):self.root = Noneif li:self.root = self.insert(self.root, li[0])for val in li[1:]:self.insert(self.root, val)def insert(self, root, val):if root is None:root = BiTreeNode(val)elif val < root.data:root.lchild = self.insert(root.lchild, val)else:root.rchild = self.insert(root.rchild, val)return rootdef insert_no_rec(self, val):p = self.rootif not p:self.root = BiTreeNode(val)returnwhile True:if val < p.data:if p.lchild:p = p.lchildelse:p.lchild = BiTreeNode(val)breakelse:if p.rchild:p = p.rchildelse:p.rchild = BiTreeNode(val)breakdef query(self, root, val):if not root:return Falseif root.data == val:return Trueelif root.data > val:return self.query(root.lchild, val)else:return self.query(root.rchild, val)def query_no_rec(self, val):p = self.rootwhile p:if p.data == val:return Trueelif p.data > val:p = p.lchildelse:p = p.rchildreturn Falsedef in_order(self, root):if root:self.in_order(root.lchild)print(root.data, end=',')self.in_order(root.rchild)tree = BST() for i in [1,5,9,8,7,6,4,3,2]:tree.insert_no_rec(i) tree.in_order(tree.root) #print(tree.query_no_rec(12)) View Code?
轉載于:https://www.cnblogs.com/mengqingjian/p/8407016.html
總結
以上是生活随笔為你收集整理的Python算法——二叉树的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 微信浏览器ISO系统底部导航栏
- 下一篇: python实现文件加密