Next, I wrote the code for finding the depth and width of a binary tree using python to find the depth and recursion. I used the queue to find the width and then the width of each layer, the greatest value is the width of the binary tree, as shown below:
import queueclass Node:def __init__(self,value=None,left=None,right=None):self.value=valueself.left=leftself.right=rightdef treeDepth(tree):if tree==None:return 0leftDepth=treeDepth(tree.left)rightDepth=treeDepth(tree.right)if leftDepth>rightDepth:return leftDepth+1if rightDepth>=leftDepth:return rightDepth+1def treeWidth(tree):curwidth=1maxwidth=0q=queue.Queue()q.put(tree)while not q.empty():n=curwidthfor i in range(n):tmp=q.get()curwidth-=1if tmp.left:q.put(tmp.left)curwidth+=1if tmp.right:q.put(tmp.right)curwidth+=1if curwidth>maxwidth:maxwidth=curwidthreturn maxwidthif __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)
Output:
depth: 4width: 3
Reprinted Please note: