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