leetcode_count-complete-tree-nodes

题目链接

count-complete-tree-nodes

题目内容

给出一个完全二叉树,求出该树的节点个数。

说明

完全二叉树的定义如下:在完全二叉树中,除了最底层节点可能没填满外,其余每层节点数都达到最大值,并且最下面一层的节点都集中在该层最左边的若干位置。若最底层为第 h 层,则该层包含 1~ 2h 个节点。

示例

输入:
1
/
2 3
/ \ /
4 5 6

输出: 6

解题思路

本题使用了递归。
1.首先判断树是否为空,为空则返回0;
2.由于是完全二叉树,对于所有的节点来说,如果有右子树就一定会有左子树,所以右子树存在时我们就可以递归1 + countNodes(root->right) + countNodes(root->left);
3.当右子树不存在而左子树存在时,递归1 + countNodes(root->left);
4.当左右子树都不存在时,递归结束,返回1。

代码

/**
 * 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;
        if(root->right)
            return 1 + countNodes(root->right) + countNodes(root->left);
        else if(root->left)
            return 1 + countNodes(root->left);
        else
            return 1;
    }
};
posted @ 2020-11-24 23:32  位军营  阅读(46)  评论(1编辑  收藏  举报