# 樹節(jié)點(diǎn)的定義
class Node(object):
def __init__(self, val=None, left=None, right=None):
self.val = val
self.left = left
self.right = right
# 三種遍歷方式
class Travaltree(object):
def __init__(self):
self.res = []
def preorder(self, root):
if root is None:
return
self.res.append(root.val)
self.preorder(root.left)
self.preorder(root.right)
return self.res
def inorder(self, root):
if root is None:
return
self.inorder(root.left)
self.res.append(root.val)
self.inorder(root.right)
return self.res
def postorder(self, root):
if root is None:
return
self.postorder(root.left)
self.postorder(root.right)
self.res.append(root.val)
return self.res
# 二叉搜索樹的構(gòu)建、插入節(jié)點(diǎn)的函數(shù)
def insert(root, val):
newnode = Node(val)
if root is None:
root = newnode
else:
temp = root
while temp is not None:
if val < temp.val:
if temp.left is None:
temp.left = newnode
return root
else:
temp = temp.left
else:
if temp.right is None:
temp.right = newnode
return root
else:
temp = temp.right
return root
# 二叉搜索樹的構(gòu)建
def build_binary_search_tree(arr):
tree = None
for item in arr:
tree = insert(tree, item)
return tree
# 獲取樹的最大高度
def get_height(root):
if root is None:
return 0
return max(get_height(root.left), get_height(root.right)) + 1
# 獲取樹中最大的值
def get_max(root):
if root is None:
return float("-inf")
if root.left is None and root.right is None:
return root.val
left_max = get_max(root.left)
right_max = get_max(root.right)
max_ = max(left_max, right_max)
max_ = max(max_, root.val)
return max_
arr = [6, 3, 8, 2, 5, 1, 7]
tree = build_binary_search_tree(arr)
travaltree = Travaltree()
preres = travaltree.preorder(tree)
travaltree.res = []
inres = travaltree.inorder(tree)
travaltree.res = []
postres = travaltree.postorder(tree)
print(preres)
print(inres)
print(postres)
height = get_height(tree)
print(height)
max_ = get_max(tree)
print(max_)
樹的基礎(chǔ)知識
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲(chǔ)服務(wù)。
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲(chǔ)服務(wù)。
相關(guān)閱讀更多精彩內(nèi)容
- 前言: 現(xiàn)在安卓面試,對于數(shù)據(jù)結(jié)構(gòu)的問題也越來越多了,也經(jīng)??吹絼e人發(fā)的面試題都是問什么紅黑樹,二叉樹查找等,所以...
- 本文首發(fā)于我的個(gè)人博客Suixin’s Blog原文: https://suixinblog.cn/2019/02...
- 1、什么是二叉樹 二叉樹是最多只有兩個(gè)子孩子的樹 2、什么是滿二叉樹 滿二叉樹就是除了最大層有葉子節(jié)點(diǎn)之外,其它層...
- 二叉樹是每個(gè)節(jié)點(diǎn)最多有兩個(gè)子樹的樹結(jié)構(gòu)。通常子樹被稱作“左子樹”(left subtree)和“右子樹”(righ...
- 經(jīng)常有同事聊到二叉樹的一些問題,大概很多人都知道二叉樹的形狀,但是它是如何遍歷的,什么是前序,中序和后序呢? 如下...