The total number of nodes for a complete binary tree python implementation

Source: Internet
Author: User

1. Use general recursion to obtain

1 def Getnodenums (head): 2     if  not Head: 3         return 0 4     Lnums = getnodenums (head.left)5     rnums = getnodenums (head.right)6     return lnums + rnums + 1

2. Recursive (Time complexity O (LOGN*LOGN)) with full binary tree characteristics

1 #using the full binary tree feature, recursive time complexity is used: O (LOGN*LOGN)2 #The total number of tree nodes with two forks is 2**n-13 defNodenums (head):4     if  notHead:5         return06     returnBS (head, 1, Mostleftlevel (head, 1)) 7 8 #total number of nodes in the current node9 defBS (node, level, height):Ten     ifLevel = =Height: One         return1 A         #If the right child node of the current node equals the parent node depth minus one, that is, the left subtree of the current node is full two-tree -     ifMostleftlevel (node.right, level+1) = =Height: -         #Returns the number of left child tree nodes + parent node + right subtree node the         return2** (Height-level) + BS (Node.right, level+1, height) -     Else:        -         #If the right child node depth is not equal to the parent node depth minus one, then this tree is a complete binary tree, that is, the right subtree is full two tree -         #Returns the number of right subtree nodes + parent node + Left child tree node +         return2** (HEIGHT-LEVEL-1) + BS (Node.left, level+1, height) -  + #to solicit the depth of the current node according to the full binary tree A defmostleftlevel (node, level): at      whilenode: -Level + = 1 -node =Node.left -     returnLevel-1

The total number of nodes for a complete binary tree python implementation

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.