二叉树的遍历

前面几种遍历方法比较简单,说明一下最后一种

1. 如果路径上前一个节点是父节点,则往左孩子方向走

2. 如果路径上前一个节点是左孩子,则往右孩子方向走

3. 如果路径上前一个节点是右孩子,则往父节点方向走

处理下孩子缺失的情况

1. 如果只有一个右孩子且从父节点过来,往右孩子方向走  (有右无左)

2. 如果从左孩子过来且无右孩子,则往父节点方向走        (有左无右)

3. 如果没有孩子节点,则往父节点走                            (无左无右)

#include <iostream>
#include <stack>
using namespace std;
struct Tree{
    Tree *parent;
    Tree *left;
    Tree *right;
    int key;
};

//递归方式 先序 中序 后序
//先序
void Ergodic_P(Tree *tree){
    if (!tree)
        return;
    cout<<tree->key;
    Ergodic_P(tree->left);
    Ergodic_P(tree->right);
}
//中序
void Ergodic_M(Tree *tree){
    if (!tree)
        return;
    
    Ergodic_M(tree->left);
    cout << tree->key;
    Ergodic_M(tree->right);
}
//后序
void Ergodic_S(Tree *tree){
    if (!tree)
        return;
    Ergodic_S(tree->left);
    Ergodic_S(tree->right);
    cout << tree->key;
}

//非递归方式
//借用栈
void Ergodic_Stack(Tree *tree){
    stack<Tree *> sta;
    sta.push(tree);
    while (!sta.empty()){
        tree = sta.top();
        sta.pop();
        cout << tree->key;
        if (tree->left)
            sta.push(tree->left);
        if (tree->right)
            sta.push(tree->right);
    }
}

//非常巧妙的一种方法

void Ergodic_Tricky(Tree *tree){
    Tree *prev = 0;
    while (tree) {
        if (prev == tree->parent) {
            cout << tree->key;
            prev = tree;
            tree = tree->left ? tree->left :
                tree->right ? tree->right :
                tree->parent;
        }
        else if (prev == tree->left && tree->right) {
            prev = tree;
            tree = tree->right;
        }
        else {
            prev = tree;
            tree = tree->parent;
        }
    }

}

int main(){
    Tree leaf_1{0,0,0,1};
    Tree leaf_2{ 0, 0, 0, 2 };
    Tree leaf_3{ 0, 0, 0, 3 };
    Tree leaf_4{ 0, 0, 0, 4 };
    Tree tree_1{ 0, &leaf_1, &leaf_2, 5 };
    Tree tree_2{ 0, &leaf_3, &leaf_4, 6 };
    Tree root{ 0, &tree_1, &tree_2, 7 };
    leaf_1.parent = &tree_1;
    leaf_2.parent = &tree_1;
    leaf_3.parent = &tree_2;
    leaf_4.parent = &tree_2;
    tree_1.parent = &root;
    tree_2.parent = &root;

    Ergodic_P(&root);
    cout << endl;
    Ergodic_P(&root);
    cout << endl;
    Ergodic_S(&root);
    cout << endl;
    Ergodic_Stack(&root);
    cout << endl;
    Ergodic_Tricky(&root);

}

 

posted on 2015-04-12 20:46  Natsukashiii  阅读(179)  评论(0编辑  收藏  举报

导航