(1)构造一棵二叉树,打印出前序遍历、中序遍历、后序遍历的遍历序列; (2)选择一种遍历方式计算该树中叶子结点的个数,并打印出叶子结点; (3)编写二叉树先序和中序非递归算法。用c++
时间: 2024-12-16 21:27:34 浏览: 18
在C++中,我们可以创建一个简单的二叉树结构,然后分别实现前序、中序和后序遍历,以及计算叶子节点数量的算法。以下是完整的代码:
```cpp
#include <iostream>
using namespace std;
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
// 前序遍历
void preOrder(TreeNode* root) {
if (root != nullptr) {
cout << root->val << " ";
preOrder(root->left);
preOrder(root->right);
}
}
// 中序遍历
void inOrder(TreeNode* root) {
if (root != nullptr) {
inOrder(root->left);
cout << root->val << " ";
inOrder(root->right);
}
}
// 后序遍历
void postOrder(TreeNode* root) {
if (root != nullptr) {
postOrder(root->left);
postOrder(root->right);
cout << root->val << " ";
}
}
// 计算叶子节点数量
int countLeaves(TreeNode* root) {
if (root == nullptr) return 0;
if (root->left == nullptr && root->right == nullptr) return 1; // 如果左右都为空,则是一个叶子节点
return countLeaves(root->left) + countLeaves(root->right);
}
int main() {
// 构造二叉树示例
TreeNode* root = new TreeNode(1);
root->left = new TreeNode(2);
root->right = new TreeNode(3);
root->left->left = new TreeNode(4);
root->left->right = new TreeNode(5);
cout << "前序遍历: ";
preOrder(root);
cout << endl;
cout << "中序遍历: ";
inOrder(root);
cout << endl;
cout << "后序遍历: ";
postOrder(root);
cout << endl;
cout << "叶子节点个数: " << countLeaves(root) << endl;
delete root;
return 0;
}
```
阅读全文