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

解题思路 —— 分治递归

如果子树是满二叉树,则计算其节点数。如果子树不是满二叉树,则分别计算子树的节点数。

AC 代码

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
    int Lh(TreeNode* root)
    {
        if(root == nullptr) return 0;
        else return Lh(root->left) + 1;
    }
    int Rh(TreeNode* root)
    {
        if(root == nullptr) return 0;
        else return Rh(root->right) + 1;
    }
public:
    int countNodes(TreeNode* root) {
        if(root == nullptr) return 0;
        else if(Lh(root) == Rh(root)) return pow(2, Lh(root))-1;
        else return countNodes(root->left) + countNodes(root->right) + 1;
    }
};