1. 程式人生 > >LeetCode-222. Count Complete Tree Nodes

LeetCode-222. Count Complete Tree Nodes

Given a complete binary tree, count the number of nodes.

Note:

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.

Example:

Input: 
    1
   / \
  2   3
 / \  /
4  5 6

Output: 6

題解:原來直接返回1 + countNodes(root->left) + countNodes(root->right)會報超時,看別人分析,滿二叉樹可以單獨處理。

class Solution {
public:
    int countNodes(TreeNode* root) {
      TreeNode *p = root, *q = root;
      if (!root){
        return 0;
      }
      int l = 0, r = 0;
      while (p){
        l++;
        p = p->left;
      }
      while (q){
        r++;
        q = q->right;
      }
      if (r == l){
        return pow(2, l) - 1;
      }
      return 1 + countNodes(root->left) + countNodes(root->right);
    }
};