前序遍历递归:
后续遍历递归
前序遍历非递归
后续遍历非递归(增加指针指向上个遍历的节点,注意栈的push顺序与前序、中序不同)
#include <vector>
#include <iostream>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
void pre_order_recursive(TreeNode* root, vector<int>& result) {
if(!root) return;
result.push_back(root->val);
if(root->left)
pre_order_recursive(root->left, result);
if (root->right)
pre_order_recursive(root->right, result);
}
/*
1
/ \
2 3
/ \ / \
4 5 6 7
*/
int main(){
TreeNode* n1 = new TreeNode(1);
TreeNode* n2 = new TreeNode(2);
TreeNode* n3 = new TreeNode(3);
TreeNode* n4 = new TreeNode(4);
TreeNode* n5 = new TreeNode(5);
TreeNode* n6 = new TreeNode(6);
TreeNode* n7 = new TreeNode(7);
n1->left = n2; n1->right = n3;
n2->left = n4; n2->right = n5;
n3->left = n6; n3->right = n7;
vector<int> res;
pre_order_recursive(n1, res);
for(int i = 0; i < res.size(); i++){
cout << res[i] << " ";
}
system("PAUSE");
}
中序遍历递归
void in_order_recursive(TreeNode* root, vector<int>& result) {
if(root->left)
in_order_recursive(root->left, result);
if(root)
result.push_back(root->val);
if(root->right)
in_order_recursive(root->right, result);
}
后续遍历递归
void post_order_recursive(TreeNode* root, vector<int>& result) {
if(root->left)
post_order_recursive(root->left, result);
if(root->right)
post_order_recursive(root->right, result);
if(root)
result.push_back(root->val);
}
前序遍历非递归
void pre_order(TreeNode* root, vector<int>& result) {
stack<TreeNode*> st;
while(root || !st.empty()){
while (root){
st.push(root);
result.push_back(root->val);
root = root->left;
}
if(!st.empty()){
root = st.top();
st.pop();
root = root->right;
}
}
}
void in_order(TreeNode* root, vector<int>& result) {
stack<TreeNode*> st;
while(root || !st.empty()){
while (root){
st.push(root);
root = root->left;
}
if(!st.empty()){
root = st.top();
result.push_back(root->val);
st.pop();
root = root->right;
}
}
}
后续遍历非递归(增加指针指向上个遍历的节点,注意栈的push顺序与前序、中序不同)
void post_order(TreeNode* root, vector<int>& result) {
stack<TreeNode*> st;
TreeNode* pre = NULL;
st.push(root);
while(!st.empty()){
root = st.top();
if((root->left == NULL && root->right == NULL) || (pre == root->right) || (root->right == NULL && pre == root->left)){
result.push_back(root->val);
cout << root->val << " ";
pre = root;
st.pop();
}
else{
if(root->right)
st.push(root->right);
if(root->left)
st.push(root->left);
}
}
}
(转)另一种方式(每个节点增加访问次数标识,push顺序与之前一致)
void postOrder2(BinTree *root) //非递归后序遍历
{
stack<BTNode*> s;
BinTree *p=root;
BTNode *temp;
while(p!=NULL||!s.empty())
{
while(p!=NULL) //沿左子树一直往下搜索,直至出现没有左子树的结点
{
BTNode *btn=(BTNode *)malloc(sizeof(BTNode));
btn->btnode=p;
btn->isFirst=true;
s.push(btn);
p=p->lchild;
}
if(!s.empty())
{
temp=s.top();
s.pop();
if(temp->isFirst==true) //表示是第一次出现在栈顶
{
temp->isFirst=false;
s.push(temp);
p=temp->btnode->rchild;
}
else //第二次出现在栈顶
{
cout<<temp->btnode->data<<" ";
p=NULL;
}
}
}
}