使用递归实现二叉树的前中后序遍历很简单,写法基本相同。但用迭代稍有不同,较递归稍难理解和记忆,但迭代效率更高。下面是用迭代实现二叉树的前中后序遍历的代码示例。当然,通过迭代实现前中后序遍历的方法有多重,这里只是其中一种实现方法。
#include <iostream>
#include <vector>
#include <stack>
using namespace std;
//Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
/*
7
/ \
4 8
/ /
9 34
*/
/*使用迭代实现二叉树的前后中序遍历*/
//前序遍历
vector<int> preOrder(TreeNode* root) {
vector<int> res;
if (root == NULL) {
return res;
}
stack<TreeNode*> st;
st.push(root);
while (st.size()) {
TreeNode* p = st.top();
st.pop();
res.push_back(p->val);
if (p->right) {
st.push(p->right);
}
if (p->left) {
st.push(p->left);
}
}
return res;
}
//后序遍历
//后序遍历是:左右根,前序遍历是:跟左右,可以先将前序遍历换成跟右左,就和前序遍历一样了
vector<int> subOrder(TreeNode* root) {
vector<int> res;
if (root == NULL) {
return res;
}
stack<TreeNode*> st;
st.push(root);
while (st.size() > 0) {
TreeNode* p = st.top();
st.pop();
res.push_back(p->val);
if (p->left) {
st.push(p->left);
}
if (p->right) {
st.push(p->right);
}
}
reverse(res.begin(), res.end());
return res;
}
//中序遍历
vector<int> inOrder(TreeNode* root) {
vector<int> res;
if (root == NULL) {
return res;
}
stack<TreeNode*> st;
TreeNode* p = root;
while (st.size() > 0 || p != NULL) {
while (p != NULL) {
st.push(p);
p = p->left;
}
if (st.size() > 0) {
p = st.top();
st.pop();
res.push_back(p->val);
p = p->right;
}
}
return res;
}
void PrintVector(vector<int> vec) {
int n = vec.size();
for (int i = 0; i < n; i++) {
cout << vec[i] << "\t";
}
cout << endl;
}
int main()
{
TreeNode n1(7);
TreeNode n2(4);
TreeNode n3(8);
TreeNode n4(9);
TreeNode n5(34);
n1.left = &n2;
n1.right = &n3;
n2.left = &n4;
n3.left = &n5;
vector<int> res = preOrder(&n1);
cout << "前序遍历为:" << endl;
PrintVector(res);
vector<int> res2 = subOrder(&n1);
cout << "后序遍历为:" << endl;
PrintVector(res2);
vector<int> res3 = inOrder(&n1);
cout << "中序遍历为:" << endl;
PrintVector(res3);
}