【Python排序搜索基本算法】之二叉树的深度和宽度
2014-04-15 09:41
746 查看
接着上一个二叉树的主题,用python写一下求二叉树深度和宽度的代码,求深度用递归;求宽度用队列,然后把每层的宽度求出来,找出最大的就是二叉树的宽度,如下:
输出为:
转载请注明:转自/article/1349970.html
import queue class Node: def __init__(self,value=None,left=None,right=None): self.value=value self.left=left self.right=right def treeDepth(tree): if tree==None: return 0 leftDepth=treeDepth(tree.left) rightDepth=treeDepth(tree.right) if leftDepth>rightDepth: return leftDepth+1 if rightDepth>=leftDepth: return rightDepth+1 def treeWidth(tree): curwidth=1 maxwidth=0 q=queue.Queue() q.put(tree) while not q.empty(): n=curwidth for i in range(n): tmp=q.get() curwidth-=1 if tmp.left: q.put(tmp.left) curwidth+=1 if tmp.right: q.put(tmp.right) curwidth+=1 if curwidth>maxwidth: maxwidth=curwidth return maxwidth if __name__=='__main__': root=Node('D',Node('B',Node('A'),Node('C')),Node('E',right=Node('G',Node('F')))) depth=treeDepth(root) width=treeWidth(root) print('depth:',depth) print('width:',width)
输出为:
depth: 4 width: 3
转载请注明:转自/article/1349970.html
相关文章推荐
- 【Python排序搜索基本算法】之深度优先搜索、广度优先搜索、拓扑排序、强联通&Kosaraju算法
- 【Python排序搜索基本算法】之深度优先搜索、广度优先搜索、拓扑排序、强联通&Kosaraju算法
- 【Python排序搜索基本算法】之二叉树的遍历
- 【Python排序搜索基本算法】之无向图的最小割&Karger算法(Graphs and Minimum Cuts & Karger's Min-Cut Algorithm)
- 【Python排序搜索基本算法】之拓扑排序
- Python排序搜索基本算法之堆排序实例详解
- Python排序搜索基本算法之希尔排序实例分析
- 【Python排序搜索基本算法】之归并排序&分治法(Merge Sort and Divide & Conquer)
- 【Python排序搜索基本算法】之希尔排序
- 【Python排序搜索基本算法】之堆排序
- 【Python排序搜索基本算法】之拓扑排序
- 【Python排序搜索基本算法】之归并排序
- 【Python排序搜索基本算法】之拓扑排序
- 【Python排序搜索基本算法】之Dijkstra算法
- 【Python排序搜索基本算法】之插入排序
- 【Python排序搜索基本算法】之插入排序
- 【Python排序搜索基本算法】之快速排序
- Python排序搜索基本算法之选择排序实例分析
- 【Python排序搜索基本算法】之快速排序(QuickSort)
- 【Python排序搜索基本算法】之Prim算法