写出非递归的方法实现对给定二叉树的先序和层序遍历算法,并给出一组数据
时间: 2023-06-16 12:06:13 浏览: 38
采用非递归对二叉树的先序、中序、后序遍历算法
5星 · 资源好评率100%
非递归的先序遍历算法:
```
void preOrder(TreeNode* root) {
if (root == nullptr) return;
stack<TreeNode*> stk;
stk.push(root);
while (!stk.empty()) {
TreeNode* cur = stk.top();
stk.pop();
cout << cur->val << " ";
if (cur->right != nullptr) stk.push(cur->right);
if (cur->left != nullptr) stk.push(cur->left);
}
}
```
非递归的层序遍历算法:
```
void levelOrder(TreeNode* root) {
if (root == nullptr) return;
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
int size = q.size();
for (int i = 0; i < size; i++) {
TreeNode* cur = q.front();
q.pop();
cout << cur->val << " ";
if (cur->left != nullptr) q.push(cur->left);
if (cur->right != nullptr) q.push(cur->right);
}
}
}
```
数据:
```
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);
```
先序遍历输出:1 2 4 5 3 6 7
层序遍历输出:1 2 3 4 5 6 7
阅读全文