创建树,遍历树,反转树
thinking:用到的思想都是递归
递归一定要有结束条件
class Bnode(object):
def __init__(self, data, left=None, right=None):
self.data = data
self.left = left
self.right = right
class Btree(object):
def __init__(self, root=None):
self.root = root
'''
build_from
:param node_list: {'data': 'A', 'left': None, 'right': None, 'is_root': False}
'''
@classmethod
def bulid(cls, list):
node_dict = {}
# 制作节点
for item in list:
data = item['data']
node_dict[data] = Bnode(data)
# 把节点组装成数
for item in list:
data = item['data']
node = node_dict[data]
if node['is_root']:
root = node
node.left = node_dict.get(item['left'])
node.right = node_dict.get(item['right'])
return cls(root)
def preorder(self, subtree):
# 先序
if subtree is not None:
print(subtree.data)
self.preorder(subtree.left)
self.preorder(subtree.right)
'''反转'''
def reverse(self, subtree):
if subtree is not None:
subtree.left, subtree.right = subtree.right, subtree.left
self.reverse(self, subtree.left)
self.reverse(self, subtree.right)
网友评论