c++二叉树的创建与遍历并求叶子节点数目完整代码
时间: 2023-12-18 09:03:38 浏览: 98
当然,下面是一个示例的完整代码,用于创建和遍历二叉树,并计算叶子节点数目。
```cpp
#include <iostream>
using namespace std;
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
// 创建二叉树
TreeNode* createBinaryTree() {
int val;
cin >> val;
if (val == -1) {
return NULL;
}
TreeNode* root = new TreeNode(val);
cout << "Enter left child of " << val << ": ";
root->left = createBinaryTree();
cout << "Enter right child of " << val << ": ";
root->right = createBinaryTree();
return root;
}
// 遍历二叉树(前序遍历)
void preOrderTraversal(TreeNode* root) {
if (root == NULL) {
return;
}
cout << root->val << " ";
preOrderTraversal(root->left);
preOrderTraversal(root->right);
}
// 计算叶子节点数目
int countLeafNodes(TreeNode* root) {
if (root == NULL) {
return 0;
}
if (root->left == NULL && root->right == NULL) {
return 1;
}
return countLeafNodes(root->left) + countLeafNodes(root->right);
}
int main() {
cout << "Enter root value (-1 for NULL): ";
TreeNode* root = createBinaryTree();
cout << "Preorder traversal: ";
preOrderTraversal(root);
cout << endl;
int leafNodeCount = countLeafNodes(root);
cout << "Number of leaf nodes: " << leafNodeCount << endl;
return 0;
}
```
这段代码实现了创建二叉树、前序遍历二叉树以及计算叶子节点数目的功能。你可以根据需要修改或扩展代码。
阅读全文