牛牛有一棵二叉树,该二叉树节点的权值为0/1。牛牛给你这棵二叉树,想让你告诉他该二叉树从根节点到叶子节点的所有路径中,节点"权值1的个数”比"权值0的个数”多1的路径有多少条呢返回路径数目。
输入:
{1,0,0,1,0,#,1}
输出:
2
说明:
my code:
import math
root = [0,1,1,0,1,1,0] # 输入值
total_count = 0 # 返回值
tree_height = int(math.log(len(root)+1,2)) # 树的高度
level = [0 for i in range(0,tree_height)] # 变量空间
path = [0 for i in range(0,pow(2,tree_height-1))] # 变量空间,路径的个数=leaves的个数
# 划分出每一层的node
position = 0 # 记录当前节点位置
for i in range(0,tree_height):# i=0,1,2
level[i] = root[position:int(position+pow(2,i))]
position = position + pow(2,i)
# 重复列表,每一层重复扩展至len(leaves)大小,方便规划出路径
for i in range(len(level)):
repeat_num = int(len(path)/len(level[i]))
level[i] = level[i]*repeat_num
print("level:",level)
# 规划出路径
for j in range(0, len(path)):
for h in range(0, len(level)):
path[j]=''.join([str(path[j]),str(level[h][j])])
print("path",path) # 这里,每一个level多算了一个0
# count每条路径的0,1个数
for i in range(0,len(path)):
num_0 = path[i].count('0')
num_1 = path[i].count('1')
if num_1 - num_0 == 0: # 因为上面每一个路径多算了一个0,所以这里根据目标调整了条件
total_count = total_count + 1
print(total_count)