考察的知识点:树的遍历、递归

题目分析:

遍历一遍树,然后记录节点数量即可。

递归时,基准条件是root为空的情况,对应树中有0个节点。然后对每一个子树,将其左子树中的节点数量加上根节点,再加上右子树中的节点数量,递归回原树的根节点时就能知道整棵树中的节点数量。

所用编程语言: C++

/**
 * struct TreeNode {
 *	int val;
 *	struct TreeNode *left;
 *	struct TreeNode *right;
 *	TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 * };
 */
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param root TreeNode类 
     * @return int整型
     */
    int countNodes(TreeNode* root) {
        // write code here
        if (!root) return 0;
        int l = countNodes(root->left);
        int r = countNodes(root->right);
        return l + r + 1;
    }
};