任意给定的二叉树完成下列操作:(1)根据输入的序列,建立二叉链表存储结构;(2)输出该二叉树的先序、中序、后序遍历结果(递归算法);(3)先序遍历二叉树(非递归算法);(4)借助队列实现二叉树的层次遍历;(5)求二叉树的高度;(6)求二叉树叶子结点个数;(7)将二叉链表视为树或森林的孩子兄弟链表,计算其叶子结点个数。请给出完整代码
时间: 2023-10-30 13:04:43 浏览: 142
以下是用C++语言实现的代码:
```cpp
#include <iostream>
#include <stack>
#include <queue>
using namespace std;
struct TreeNode{
char val;
TreeNode* left;
TreeNode* right;
TreeNode(char x) : val(x), left(NULL), right(NULL) {}
};
// 先序遍历(递归算法)
void preorderTraversal(TreeNode* root) {
if (root == NULL) return;
cout << root->val << " ";
preorderTraversal(root->left);
preorderTraversal(root->right);
}
// 中序遍历(递归算法)
void inorderTraversal(TreeNode* root) {
if (root == NULL) return;
inorderTraversal(root->left);
cout << root->val << " ";
inorderTraversal(root->right);
}
// 后序遍历(递归算法)
void postorderTraversal(TreeNode* root) {
if (root == NULL) return;
postorderTraversal(root->left);
postorderTraversal(root->right);
cout << root->val << " ";
}
// 先序遍历(非递归算法)
void preorderTraversalNonRecursive(TreeNode* root) {
if (root == NULL) return;
stack<TreeNode*> st;
st.push(root);
while (!st.empty()) {
TreeNode* node = st.top();
st.pop();
cout << node->val << " ";
if (node->right) st.push(node->right);
if (node->left) st.push(node->left);
}
}
// 层次遍历
void levelOrderTraversal(TreeNode* root) {
if (root == NULL) return;
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
TreeNode* node = q.front();
q.pop();
cout << node->val << " ";
if (node->left) q.push(node->left);
if (node->right) q.push(node->right);
}
}
// 求二叉树的高度
int getHeight(TreeNode* root) {
if (root == NULL) return 0;
int leftHeight = getHeight(root->left);
int rightHeight = getHeight(root->right);
return max(leftHeight, rightHeight) + 1;
}
// 求二叉树叶子节点个数
int getLeafCount(TreeNode* root) {
if (root == NULL) return 0;
if (root->left == NULL && root->right == NULL) return 1;
return getLeafCount(root->left) + getLeafCount(root->right);
}
// 将二叉树的孩子兄弟链表视为树或森林,计算其叶子节点个数
int getLeafCountAsTree(TreeNode* root) {
if (root == NULL) return 0;
if (root->left == NULL && root->right == NULL) return 1;
return getLeafCountAsTree(root->left) + getLeafCountAsTree(root->right);
}
// 根据输入的序列建立二叉树
TreeNode* buildTree(string s, int& i) {
if (i >= s.size() || s[i] == '#') {
i++;
return NULL;
}
TreeNode* root = new TreeNode(s[i]);
i++;
root->left = buildTree(s, i);
root->right = buildTree(s, i);
return root;
}
int main() {
string s = "AB#D##CE##F##";
int i = 0;
TreeNode* root = buildTree(s, i);
cout << "先序遍历结果(递归算法):";
preorderTraversal(root);
cout << endl;
cout << "中序遍历结果(递归算法):";
inorderTraversal(root);
cout << endl;
cout << "后序遍历结果(递归算法):";
postorderTraversal(root);
cout << endl;
cout << "先序遍历结果(非递归算法):";
preorderTraversalNonRecursive(root);
cout << endl;
cout << "层次遍历结果:";
levelOrderTraversal(root);
cout << endl;
cout << "二叉树的高度为:" << getHeight(root) << endl;
cout << "二叉树叶子节点个数为:" << getLeafCount(root) << endl;
cout << "二叉树孩子兄弟链表的叶子节点个数为:" << getLeafCountAsTree(root) << endl;
return 0;
}
```
阅读全文