[leetcode] 222. Count Complete Tree Nodes

Description

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

分析

题目的意思是:给定一个完全二叉树,求其结点的个数。

  • 完全二叉树有一个很好的性质,对任一结点,如果其右子树的最大层次为L,则其左子树的最大层次为L或L+l。那么我们可以根据这个规律,分别求出左右子树的高度。如果左右高度一致,则为满二叉树,直接算出结点数就行了;否则分别递归左右子树。

代码

/**
 * 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 {
public:
    int countNodes(TreeNode* root) {
        if(!root){
            return 0;
        }
        int lh=leftHeight(root);
        int rh=rightHeight(root);
        if(lh==rh) return pow(2,lh)-1;
        return countNodes(root->left)+countNodes(root->right)+1;
    }
    int leftHeight(TreeNode* root){
        if(!root){
            return 0;
        }
        return leftHeight(root->left)+1;
    }
    int rightHeight(TreeNode* root){
        if(!root){
            return 0;
        }
        return rightHeight(root->right)+1;
    }
};

参考文献

[LeetCode] Count Complete Tree Nodes 求完全二叉树的节点个数
完全二叉树

你可能感兴趣的:(leetcode,C++,leetcode题解)