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.
Total binary tree compared to ordinary binary trees, when counting a trick is when the last layer is full (the left depth is equal to the right depth),
Does not need to be counted by traverse way, directly equals 2^h-1
/** 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; TreeNode* L =Root; intLefth =0; while(l->Left ) {lefth++; L= l->Left ; } TreeNode* r =Root; intRighth =0; while(r->Right ) {righth++; R= r->Right ; } if(Lefth = =righth)returnPow2.0, lefth+1) -1; Else return 1+ countnodes (root->left) + countnodes (root->Right ); }};
"Leetcode" 222. Count Complete Tree Nodes