(1)采用二叉链表存储结构,完成二叉树的层次遍历,先序遍历的非递归算法和中序遍历的非递归算法。代码
时间: 2024-04-29 08:21:25 浏览: 111
以下是采用二叉链表存储结构实现二叉树的层次遍历、先序遍历和中序遍历的非递归算法的代码(C++实现):
```c++
#include<iostream>
#include<queue>
using namespace std;
//二叉树结点的定义
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
//二叉树的层次遍历
void levelOrder(TreeNode* root) {
if (!root) 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);
}
cout << endl;
}
//二叉树的先序遍历
void preOrder(TreeNode* root) {
if (!root) 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);
}
cout << endl;
}
//二叉树的中序遍历
void inOrder(TreeNode* root) {
if (!root) return;
stack<TreeNode*> st;
TreeNode* node = root;
while (node || !st.empty()) {
while (node) {
st.push(node);
node = node->left;
}
node = st.top();
st.pop();
cout << node->val << " ";
node = node->right;
}
cout << endl;
}
//测试
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);
root->right->left = new TreeNode(6);
root->right->right = new TreeNode(7);
cout << "层次遍历:";
levelOrder(root);
cout << "先序遍历:";
preOrder(root);
cout << "中序遍历:";
inOrder(root);
return 0;
}
```
输出结果为:
```
层次遍历:1 2 3 4 5 6 7
先序遍历:1 2 4 5 3 6 7
中序遍历:4 2 5 1 6 3 7
```
其中,层次遍历使用了队列,先将根节点入队,然后循环从队列中取出一个结点,打印其值,并将其左右子节点入队。这样就可以按照层次遍历的顺序遍历整个二叉树。
先序遍历和中序遍历使用了栈,栈中保存的是待访问的结点。先序遍历从根节点开始,每次取出栈顶结点并打印,然后先将右子节点入栈,再将左子节点入栈。中序遍历先将左子节点全部入栈,然后取出栈顶结点并打印,最后将右子节点入栈。这样就可以按照先序遍历和中序遍历的顺序遍历整个二叉树。
阅读全文