Leetcode Count Complete Tree Nodes

Source: Internet
Author: User

Leetcode Count Complete Tree nodes topic

Ideas

The tree will be very gray;
Calculate the depth two times along the left and right. Assuming the depth of the same as the direct formula calculation.
Assume that the depth is not the same. Then find the breakpoint at the top level.

Code
intMaxd, num;intCaldeepfromright (structtreenode* root) {intAns =0; while(Root)        {ans++;    root = root->right; }returnAns;}intCaldeepfromleft (structtreenode* root) {intAns =0; while(Root)        {ans++;    root = root->left; }returnAns;}voidFindbreakpoint (structtreenode* Root,intPosintDeep) {if(num! =-1)return;if(root = NULL && deep = = Maxd) {num =1;int Base=1; for(inti =1; I < deep-1; i++) num + = (Base*=2); num + = pos;return; }Else{if(Root = NULL)return; Findbreakpoint (Root->left, POS *2, Deep +1); Findbreakpoint (Root->right, POS *2+1, Deep +1); }}intCountnodes (structtreenode* root) {intld = Caldeepfromleft (root), RD = Caldeepfromright (root); Maxd = ld;if(ld = = rd) {if(LD = =0)return 0;int Base=1; num =1; for(inti =1; i < LD; i++) num + = (Base*=2); }Else{num =-1; Findbreakpoint (Root,0,1); }returnNum;}

Leetcode 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.