c++统计二叉搜索树的节点数
时间: 2024-06-13 22:08:59 浏览: 64
以下是C++统计二叉搜索树节点数的代码实现:
```c++
#include <iostream>
using namespace std;
// 定义二叉搜索树节点结构体
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
// 统计二叉搜索树节点数
int countNodes(TreeNode* root) {
if (root == NULL) {
return 0; }
return 1 + countNodes(root->left) + countNodes(root->right);
}
int main() {
// 构建二叉搜索树
TreeNode* root = new TreeNode(4);
root->left = new TreeNode(2);
root->right = new TreeNode(6);
root->left->left = new TreeNode(1);
root->left->right = new TreeNode(3);
root->right->left = new TreeNode(5);
root->right->right = new TreeNode(7);
// 统计节点数并输出
int count = countNodes(root);
cout << "The number of nodes in the binary search tree is: " << count << endl;
return 0;
}
```
阅读全文