【LeetCode】222. 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, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h.

Solution 1
 1 class Solution {
 2 public:
 3     int countNodes(TreeNode* root) {
 4         int lh = 0, rh = 0;
 5         TreeNode* lch = root, *rch = root;
 6         
 7         while (lch) {
 8             ++lh;
 9             lch = lch->left;
10         }
11         while (rch) {
12             ++rh;
13             rch = rch->right;
14         }
15         if (lh == rh)
16             return pow(2, lh) - 1;
17         return countNodes(root->left) + countNodes(root->right) + 1;
18     }
19 };
原文地址:https://www.cnblogs.com/Atanisi/p/8834282.html