右二叉树、左二叉树、完全二叉树构建方法以及遍历索引计算公式
一、右二叉树、左二叉树、完全二叉树构建方法
# -*- coding: UTF-8 -*-
class TreeNode:
def __init__(self, name):
self._name = name
self._left_node = None
self._right_node = None
class Tree:
root = None
nodes = []
def add_node(self, name, index):
node = TreeNode(name)
if is None:
class TreeNode:
def __init__(self, name):
self._name = name
self._left_node = None
self._right_node = None
class Tree:
root = None
nodes = []
def add_node(self, name, index):
node = TreeNode(name)
if is None:
= node
des.append(node)
else:
# #构建右二叉树
# tmp_node = des[index + index % 2 - 2]
# #构建左二叉树
# tmp_node = des[((index + index % 2 -3)+abs(index + index % 2 -3))//2]
#构建完全二叉树
tmp_node = des[(index + index % 2 -2)//2]
if tmp_node._left_node is None:
二叉树的遍历及应用实验报告 tmp_node._left_node = node
des.append(tmp_node._left_node)
elif tmp_node._right_node is None:
tmp_node._right_node = node
des.append(tmp_node._right_node)
des.append(node)
else:
# #构建右二叉树
# tmp_node = des[index + index % 2 - 2]
# #构建左二叉树
# tmp_node = des[((index + index % 2 -3)+abs(index + index % 2 -3))//2]
#构建完全二叉树
tmp_node = des[(index + index % 2 -2)//2]
if tmp_node._left_node is None:
二叉树的遍历及应用实验报告 tmp_node._left_node = node
des.append(tmp_node._left_node)
elif tmp_node._right_node is None:
tmp_node._right_node = node
des.append(tmp_node._right_node)
if __name__ == '__main__':
tree = Tree()
all_node = ["Root", "Node1", "Node2", "Node3",
"Node4", "Node5", "Node6", "Node7",
"Node8", "Node9", "Node10","Node11", "Node12", "Node13",
"Node14"]
total = len(all_node)
for i, val in enumerate(all_node):
tree.add_node(val, i)
tree = Tree()
all_node = ["Root", "Node1", "Node2", "Node3",
"Node4", "Node5", "Node6", "Node7",
"Node8", "Node9", "Node10","Node11", "Node12", "Node13",
"Node14"]
total = len(all_node)
for i, val in enumerate(all_node):
tree.add_node(val, i)
二、右二叉树、左二叉树、完全二叉树遍历索引计算公式:
2.1右二叉树遍历索引表达式:index + index % 2 - 2
2.2左二叉树遍历索引表达式:((index + index % 2 -3)+abs(index + index % 2 -3))//2
2.3完全二叉树遍历索引表达式:(index + index % 2 -2)//2
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论