这篇文章主要介绍了python使用递归的方式建立二叉树,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
树和图的数据结构,就很有意思啦。
# coding = utf-8
class BinaryTree:
def __init__(self, root_obj):
self.key = root_obj
self.left_child = None
self.right_child = None
def insert_left(self, new_node):
node = BinaryTree(new_node)
if self.left_child is None:
self.left_child = node
else:
node.left_child = self.left_child
self.left_child = node
def insert_right(self, new_node):
node = BinaryTree(new_node)
if self.right_child is None:
self.right_child = node
else:
node.right_child = self.right_child
self.right_child = node
def get_right_child(self):
return self.right_child
def get_left_child(self):
return self.left_child
def set_root_val(self, obj):
self.key = obj
def get_root_val(self):
return self.key
root = BinaryTree('a')
print(root.get_root_val())
print(root.get_left_child())
root.insert_left('b')
print(root.get_left_child())
print(root.get_left_child().get_root_val())
root.insert_right('c')
print(root.get_right_child())
print(root.get_right_child().get_root_val())
root.get_right_child().set_root_val('hello')
print(root.get_right_child().get_root_val())
C:\Users\Sahara\.virtualenvs\test\Scripts\python.exe C:/Users/Sahara/PycharmProjects/test/python_search.py
a
None
<__main__.BinaryTree object at 0x00000000024139B0>
b
<__main__.BinaryTree object at 0x00000000024139E8>
c
hello
Process finished with exit code 0
Python实现二叉树遍历的递归和非递归算法
前序遍历
# -----------前序遍历 ------------
# 递归算法
def pre_order_recursive(self, T):
if T == None:
return
print(T.root, end=' ')
self.p