实现二叉树的创建及线索化的完整代码,要求如下: 1.创建二叉树 2.中序递归和非递归遍历 3.中序线索化二叉树 4.利用中序线索化二叉树实现二叉树的中序遍历 5.菜单提示操作
时间: 2024-08-13 20:06:04 浏览: 51
PHP基于非递归算法实现先序、中序及后序遍历二叉树操作示例
首先,让我们逐步介绍如何实现这些功能:
**1. 创建二叉树:**
```cpp
template <typename T>
struct TreeNode {
T val;
TreeNode* left;
TreeNode* right;
TreeNode(T x) : val(x), left(nullptr), right(nullptr) {}
};
// 创建二叉树(例如从数组或用户输入)
void createBinaryTree(TreeNode<T>*& root, const std::vector<T>& values) {
if (values.empty()) return;
root = new TreeNode(values);
int i = 1;
for (auto it = values.begin(); it != values.end(); ++it) {
if (*it < root->val) {
createBinaryTree(root->left, std::vector<T>(*it, values[i++]));
} else {
createBinaryTree(root->right, std::vector<T>(*it, values[i++]));
}
}
}
```
**2. 中序递归遍历:**
```cpp
void inorderTraversal(TreeNode<T>* root) {
if (root == nullptr) return;
inorderTraversal(root->left);
std::cout << root->val << " ";
inorderTraversal(root->right);
}
```
**3. 中序非递归遍历(使用栈):**
```cpp
std::vector<T> inorderTraversalNonRecursive(TreeNode<T>* root) {
std::vector<T> result;
stack<TreeNode<T>*> s;
TreeNode<T>* curr = root;
while (curr != nullptr || !s.empty()) {
while (curr != nullptr) {
s.push(curr);
curr = curr->left;
}
curr = s.top();
s.pop();
result.push_back(curr->val);
curr = curr->right;
}
return result;
}
```
**4. 中序线索化二叉树:**
```cpp
void线索化(TreeNode<T>*& root) {
if (root == nullptr) return;
线索化(root->left);
root->left = (root->left == nullptr) ? nullptr : &(*root->left).successor;
root->right = &(*root).successor;
root->successor = nullptr;
if (root->left != nullptr) root->left->predecessor = root;
if (root == root->parent->right) root->parent->successor = root;
}
// 非线索化(用于测试)
void unleadify(TreeNode<T>*& root) {
if (root == nullptr) return;
root->left = root->left->predecessor;
root->right = root->right->predecessor;
root->predecessor = nullptr;
root->successor = nullptr;
}
```
**5. 菜单提示操作:**
```cpp
void menu() {
int choice;
do {
cout << "1. Create binary tree\n";
cout << "2. Inorder traversal (recursive)\n";
cout << "3. Inorder traversal (non-recursive)\n";
cout << "4.线索化二叉树\n";
cout << "5. 非线索化二叉树\n";
cout << "6. Exit\n";
cin >> choice;
switch (choice) {
// 添加对应操作的实现
}
} while (choice != 6);
}
```
阅读全文