1. Description of the problem
Calculates the number of nodes for a complete binary tree. For the definition of a complete binary tree, refer to Wikipedia above.
2. Methods and Ideas
The simplest and easiest way is to use recursion to calculate the number of nodes in the left and right sub-trees, respectively. However, this method is most likely to time out, generally undesirable.
int countNodes(TreeNode* root) { if==NULLreturn0; elseif(root->==NULLreturn1; return countNodes(root->+ countNodes(root->right); }
Using this code to submit, it is still timed out. So how to improve it?
That's to simplify the algorithm with a full two-fork tree. The number of node points in a two-fork tree is calculated as N = 2^h-1. H is the number of layers of the two-fork tree. The recursive process is as follows:
- Determine if the current node is the root node is a full two tree, if the number of nodes and return, or continue to execute down.
- The Saozi right subtree of the current node is judged separately, plus one, which indicates the node count.
/** * 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 Nodesofman(treenode* Root) {//Determine if the tree is full two, if it returns the number of nodes that are full of two forks. intL=1, r=1; TreeNode *node = root; while(Node->left) {l++; node = node->left; } node = root; while(Node->right) {r++; node = node->right; }if(L = = r)return(int) Pow (2,(Double) L)-1;Else return 0; }intCountnodes (treenode* root) {if(Root = NULL)return 0;//else if (root->left = = NULL) return 1; if(Nodesofman (Root))returnNodesofman (root);Else returnCountnodes (Root->left) + countnodes (root->right) +1; }};
Leetcode 222 Count Complete Tree Nodes (calculates the total number of binary tree nodes)