日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

Python算法——二叉树

發布時間:2023/12/10 python 35 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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算法——二叉树的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。