二叉树python实现
source link: https://liangyaorong.github.io/blog/2017/%E4%BA%8C%E5%8F%89%E6%A0%91python%E5%AE%9E%E7%8E%B0/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
二叉树python实现
# coding:utf-8
class Binary_Tree(object):
def __init__(self, val=None):
self.root = val
self.left = None
self.right = None
def insert_node(tree, val):
'''插入节点'''
val_node = Binary_Tree(val)
if tree.root is None:
tree.root = val
else:
if tree.root < val:
if tree.right:
insert_node(tree.right, val)
else:
tree.right = val_node
if tree.root > val:
if tree.left:
insert_node(tree.left, val)
else:
tree.left = val_node
return tree
def build_tree(tree, val_list):
'''根据列表创建二叉树'''
for val in val_list:
insert_node(tree, val)
return tree
def pre_order_print(tree, pre_list = []):
'''前序遍历'''
if tree is not None:
pre_list.append(tree.root)
pre_order_print(tree.left, pre_list)
pre_order_print(tree.right, pre_list)
return pre_list
def in_order_print(tree, in_list = []):
'''中序遍历'''
if tree is not None:
in_order_print(tree.left, in_list)
in_list.append(tree.root)
in_order_print(tree.right, in_list)
return in_list
def post_order_print(tree, post_list = []):
'''后序遍历'''
if tree is not None:
post_order_print(tree.left, post_list)
post_order_print(tree.right, post_list)
post_list.append(tree.root)
return post_list
def find_min(tree):
'''查找最小值'''
while tree.left is not None:
tree = tree.left
return tree.root
def find_max(tree):
'''查找最大值'''
while tree.right is not None:
tree = tree.right
return tree.root
def find_val(tree, val):
'''查找特定值'''
find = False
while tree is not None:
if tree.root > val:
tree = tree.left
elif tree.root < val:
tree = tree.right
elif tree.root == val:
find = True
print "finding %s successfully" % val
break
if find is False:
print "can not find %s" % val
return find
if __name__ == '__main__':
bt = Binary_Tree()
bt = build_tree(bt, [4,6,5,9,1,12,7,10])
find_val(bt, 18)
Recommend
-
42
每日前端夜话 0xA8 每日前端夜话,陪你聊前端。 每天晚上18:00准时推送。 正文共:3742 字 预计阅...
-
19
什么是二叉树 在了解二叉查找树之前,我们行了解一下树的概念。树由节点和层级关系组成,是一种非线性的数据结构。就像现实中树的叶子和枝干一样。树枝把树叶一片片连接起来,树叶就是节点,树枝就是路径。像这样
-
18
上一篇 我们简单介绍了什么是二叉查找树,并实现了该结构。 这一篇我们来看如何遍历二叉树。常用的三种遍历方式有“先序” “中序” “后序”。对于二次查找树来说,中序遍历刚好可以得到一个有序的结果(即排序)。三种遍历方式的定...
-
14
数据结构与算法的JavaScript实现及应用 – 二叉查找树 在这篇文章里,我将介绍二叉查找树的基本操作和应用。 我们将看到二叉查找树操作的JavaScript的递归实现。由于递归受堆栈深度的限制,我们还将考虑非递归的实现。
-
6
golang二叉树翻转(递归与非递归实现)
-
5
二叉树、红黑树以及Golang实现红黑树 - GoHackers - 开发者头条 微博 使用《开发者头条》客户端,拥有更好的阅读体验。 立即体验
-
0
二叉搜索树(binary search tree)是一种特殊的二叉树,满足如下性质:(1)每个结点的关键码大于其左子树结点的关键码(如果有的情况)(2)每个结点的管家码小于其右子树结点的关键码(如果有的情况)(3)根据(1)和(2)BST不允许有重复...
-
4
二叉搜索树 二叉搜索树结合了无序链表插入便捷和有序数组二分查找快速的特点,较为高效地实现了有序符号表。下图显示了二叉搜索树的结构特点(图片来自《算法第四版》):
-
4
二叉搜索树 - C++ 实现 📌 概述 Overview 二叉查找树(英语:Binary Search Tree, 后文中简称 BST), 也称为二叉搜索树、有序二叉树(ordered b...
-
4
树的基本概念和结构 树的相关概念 节点的...
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK