Leetcode 222. Count Complete Tree Nodes

Source: Internet
Author: User

Complete binary tree: The nodes of each row except the last row have two sons, and the last row of nodes is left as far as possible.

VER0:

1 class Solution {2public:3     int countnodes (treenode* root) {4         ifreturn0 ; 5         return 1 + countnodes (root->left) + countnodes (root-> right); 6     }7 };

Not surprisingly, tle.

Ver1:

1 classSolution {2  Public:3     intCountnodes (treenode*root) {4         if(!root)return 0;5treenode* L = root, * r =Root;6         intLlen =0, Rlen =0;7         //While (l->left) {//error! Correct:while (L)8         //++llen;9         //L = l->left;Ten         // } One         //While (r->right) { A         //++rlen; -         //r = r->right; -         // } the          for(; l!=null; ++llen, l=l->Left ); attention! -          for(; r!=null; ++rlen, r=r->Right ); -         returnLlen = = Rlen? (1<<llen)-1:1+ countnodes (root->left) + countnodes (root->Right );//attention -          +          -     } +};

According to the last line of the node as far as possible on the left this feature, first calculate root->left->left-> This path is long and root->right->right-> This is a long path. If they are equal, the whole tree is full, using the geometric series formula (note that bit arithmetic is used), and the unequal is recursive.

Leetcode 222. Count Complete Tree Nodes

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.