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 2hnodes inclusive at the last level H.
Method 1: Recursion
From Root, always to the left depth = = always to the right of the depth, then the root is a full two fork tree, the number of nodes is 2^height-1
If not, then the number of nodes is Countnodes (root->left) + countnodes (root->right) + 1;
1 /**2 * Definition for a binary tree node.3 * struct TreeNode {4 * int val;5 * TreeNode *left;6 * TreeNode *right;7 * TreeNode (int x): Val (x), left (null), right (null) {}8 * };9 */Ten classSolution { One Public: A intCountnodes (treenode*root) { - if(Root = =NULL) { - return 0; the } - intLeft_height = Get_height (Root,true); Start from Root - intRight_height = Get_height (Root,false); - if(Left_height = =right_height) { + returnPow2, Left_height)-1; - } + returnCountnodes (Root->left) + countnodes (root->right) +1; A } at Private: - intGet_height (TreeNode *root,BOOLtoleft) { - if(Root = =NULL) { - return 0; - } - if(toleft) { in returnGet_height (Root->left,true) +1; - } to returnGet_height (Root->right,false) +1; + - } the};
Count Complete Tree Nodes