1. The easiest way to think: recursively traverse each point, calculate the total number of points, time complexity O (n), unfortunately, timed out. (It's not too good to be justified. = =)
Class Solution {public: int countnodes (treenode* root) { if (root==null) return 0; int res=0; if (root->left) res+=countnodes (root->left); if (root->right) res+=countnodes (root->right); return res+1;} ;
2. We should make full use of the nature of the full binary tree, originally wanted to use the law, so that only the last layer of the knot points can be, but not the implementation. So we put the problem to the overall situation, under what circumstances can use the full binary tree of the nature of the use of geometric series and directly to find it? Obviously, when the height of the subtree is equal. Therefore, we also found the condition of recursive termination, problem solving, complexity O (logn).
Class Solution {public: int countnodes (treenode* root) { if (root==null) return 0; int lno=0,rno=0; TreeNode *l=root,*r=root; while (L->left) { lno++; l=l->left; } while (R->right) { rno++; r=r->right; } if (Lno==rno) return pow (2.0,lno+1)-1; Return 1+countnodes (Root->left) +countnodes (root->right); };
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
[Leetcode] 222 Count complete Tree Nodes