我尽力了。。。具体绘制树的代码大体懂个意思,书上没讲视频没说,比较难理解。
from math import log
import operator
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
"""求树的叶子节点数"""
def getNumLeafs(myTree):
numLeafs = 0
firstStr = list(myTree.keys())[0] # 取根节点的特征
secondDict = myTree[firstStr] # 取里边一层的字典树
for key in list(secondDict.keys()): # 特征对应的值,key为0或者1
if type(secondDict[key]).__name__ == 'dict': # 如果对应的值还是字典树,代表没有遍历完
numLeafs += getNumLeafs(secondDict[key])
else:
numLeafs += 1
return numLeafs
"""求树的层数"""
def getTreeDepth(myTree):
maxDepth = 0
firstStr = list(myTree.keys())[0]
secondDict = myTree[firstStr]
for key in list(secondDict.keys()):
if type(secondDict[key]).__name__ == 'dict':
thisDepth = 1 + getTreeDepth(secondDict[key])
else:
thisDepth = 1
if thisDepth > maxDepth:
maxDepth = thisDepth
return maxDepth
"""绘制结点"""
def plotNode(nodeTxt, centerPt, parentPt, nodeType):
arrow_args = dict(arrowstyle="<-") # 定义箭头格式
font = FontProperties('SimHei') # 设置字体为黑体
createPlot.ax1.annotate(nodeTxt, xy=parentPt, xycoords='axes fraction', xytext=centerPt, textcoords='axes fraction',
va="center", ha="center", bbox=nodeType, arrowprops=arrow_args,
FontProperties=font) # 反正就