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.
Thinking of solving problems
A full traversal will time out. The height of the right subtree of Saozi can be calculated from the root node, respectively. If the assumption is equal, then the tree is full two, and the number of nodes is 2 n ? 1 。 Assuming the height is unequal, the number of nodes is left dial hand tree node number + Right sub-tree node number +1. (height n is the height that includes the root node)
Implementation code
//runtime:100 MS/** * 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) {intLefthight = GetLeft (root);intRightheight = GetRight (root);if(Lefthight = = rightheight) {returnPow2, Lefthight)-1; }return 1+ countnodes (root->left) + countnodes (root->right); }Private:int GetLeft(TreeNode *root) {intHeight =0; while(Root) {height++; root = root->left; }returnHeight }intGetRight (TreeNode *root) {intHeight =0; while(Root) {height++; root = root->right; }returnHeight }};
[Leetcode] Count Complete Tree Nodes