Topic:
Count Complete Tree Nodes
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.
Answer 1, (Error)
/** Definition for a binary tree node. * struct TreeNode {* int val; * TreeNode *left; * TreeNode *right; * TreeNode (int x): Val (x), left (null), right (NULL) {} *}; */classSolution { Public: intCountnodes (treenode*root) { if(Root = =NULL)return 0; //int leftheight = 0; //int rightheight = 0; //TreeNode *pleft = root; //While (pleft) {//++leftheight; //Pleft = pleft->left; // } //TreeNode *pright = root; //While (pright) {//++rightheight; //pright = pright->right; // } //if (leftheight = = rightheight)//return Pow (2, leftheight)-1; returnCountnodes (Root->left) + countnodes (root->right) +1; }};
Answer, correct:
The upper middle Code of the anti-comment off, run through.
Experience:
This topic, need to use to two tree node number of 2 of the N minus 1, and when we do the topic, usually do is the form of a previous solution.
This topic, mixed up with two fork tree to find the number of nodes, and the nature of the complete binary tree. Of course, I only did the previous answer, the test code reporting efficiency is not high, the time has exceeded the maximum time. Then the middle code is in the back.
Exercises (eight)