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.
Subscribe to see which companies asked this question
Answer
This topic because is a completely binary tree, so the number of nodes can be optimized, when exactly full when the number of nodes directly calculated, rather than continue to use recursion ... Otherwise there is a point that will not get through ...
/** Definition for a binary tree node. * struct TreeNode {* int val; * struct TreeNode *left; * struct TR Eenode *right; * }; */intCountnodes (structtreenode*root) { intLevel =0; structTreeNode *node_1 = root, *node_2 =Root; while(NULL! = node_1&&null! =node_2) {Node_1= node_1->Left ; Node_2= node_2->Right ; level++; } if(NULL! =node_1) { returnCountnodes (Root->left) + countnodes (root->right) +1; } Else{ returnPow2, level)-1; }}
Leetcode OJ 222. Count Complete Tree Nodes