Given a complete binary tree, count the number of nodes.
Definition of a complete binary tree from Wikipedia:
In a complete binary tree every level, except possibly the last, was completely filled, and all nodes As far left as possible. It can has between 1 and 2h nodes inclusive at the last level H.
Idea: Calculate the left and right sub-tree separately, then return to the left and right words node number plus one
Recursive method: (Timed out)
class solution {public : int countnodes (treenode* root) {if (Root = = null ) return 0 ; int lcount=0 , rcount= 0 ; if (Root->left ! = null ) {lcount = Countnodes (Root->left ); } if (Root->right ! = null ") {Rcount = Countnodes (Root->right ); } return Lcount+rcount+1 ; }};
Method Two:
First calculate the depth of the left and right are equal, equal to full two fork tree, the number of nodes full two tree is the depth of the square minus one, that is, depth^2-1; if not equal, recursively computes the Saozi right subtree in the same way and returns the sum of the two numbers plus one.
Code (c + +):
/** * Definition for a binary tree node. * struct TreeNode {* int val; * TreeNode *left; * TreeNode *righ T * TreeNode (int x): Val (x), left (null), right (NULL) {} *}; */Class Solution { Public:int Countnodes(treenode* Root) {if(Root = NULL)return 0;intLdepth = getleftdepth (root);intRdepth = getrightdepth (root);//return The square of Leftdepth-1 if(ldepth = = rdepth)return(1<< ldepth)-1;returnCountnodes (Root->left) +countnodes (root->right) +1; }//compute The depth of the left tree intGetleftdepth (TreeNode *root) {intdepth =0; while(Root) {depth++; root = root->left; }returnDepth }//compute The depth of right tree intGetrightdepth (TreeNode *root) {intdepth =0; while(Root) {depth++; root = root->right; }returnDepth }};
Leetcode[222]-count Complete Tree Nodes