Depth and width of a binary tree based on the Basic Python Sorting Algorithm

Source: Internet
Author: User

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:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.