C++使用递归和非递归遍历二叉树
时间: 2023-06-29 07:15:14 浏览: 100
二叉链树遍历(递归) C++
遍历二叉树有三种方式,分别是前序遍历、中序遍历和后序遍历。其中,前序遍历指先遍历根节点,再遍历左子树和右子树;中序遍历指先遍历左子树,再遍历根节点和右子树;后序遍历指先遍历左子树和右子树,再遍历根节点。下面是使用递归和非递归方式遍历二叉树的示例代码:
```c++
#include <iostream>
#include <stack>
using namespace std;
// 二叉树结点的定义
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
// 递归前序遍历
void preorderTraversalRecursive(TreeNode* root) {
if (root == NULL) return;
cout << root->val << " ";
preorderTraversalRecursive(root->left);
preorderTraversalRecursive(root->right);
}
// 非递归前序遍历
void preorderTraversalIterative(TreeNode* root) {
if (root == NULL) return;
stack<TreeNode*> s;
s.push(root);
while (!s.empty()) {
TreeNode* node = s.top();
s.pop();
cout << node->val << " ";
if (node->right != NULL) s.push(node->right);
if (node->left != NULL) s.push(node->left);
}
}
// 递归中序遍历
void inorderTraversalRecursive(TreeNode* root) {
if (root == NULL) return;
inorderTraversalRecursive(root->left);
cout << root->val << " ";
inorderTraversalRecursive(root->right);
}
// 非递归中序遍历
void inorderTraversalIterative(TreeNode* root) {
if (root == NULL) return;
stack<TreeNode*> s;
TreeNode* node = root;
while (node != NULL || !s.empty()) {
while (node != NULL) {
s.push(node);
node = node->left;
}
node = s.top();
s.pop();
cout << node->val << " ";
node = node->right;
}
}
// 递归后序遍历
void postorderTraversalRecursive(TreeNode* root) {
if (root == NULL) return;
postorderTraversalRecursive(root->left);
postorderTraversalRecursive(root->right);
cout << root->val << " ";
}
// 非递归后序遍历
void postorderTraversalIterative(TreeNode* root) {
if (root == NULL) return;
stack<TreeNode*> s1, s2;
s1.push(root);
while (!s1.empty()) {
TreeNode* node = s1.top();
s1.pop();
s2.push(node);
if (node->left != NULL) s1.push(node->left);
if (node->right != NULL) s1.push(node->right);
}
while (!s2.empty()) {
cout << s2.top()->val << " ";
s2.pop();
}
}
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 << "递归前序遍历:";
preorderTraversalRecursive(root);
cout << endl;
cout << "递归中序遍历:";
inorderTraversalRecursive(root);
cout << endl;
cout << "递归后序遍历:";
postorderTraversalRecursive(root);
cout << endl;
// 非递归遍历
cout << "非递归前序遍历:";
preorderTraversalIterative(root);
cout << endl;
cout << "非递归中序遍历:";
inorderTraversalIterative(root);
cout << endl;
cout << "非递归后序遍历:";
postorderTraversalIterative(root);
cout << endl;
return 0;
}
```
注意,非递归方式需要使用栈来存储待遍历的结点,同时也需要注意遍历顺序。
阅读全文