二叉树的遍历

二叉树的先序遍历顺序为:父亲->左儿子->右儿子

中序遍历顺序为:左儿子->父亲->右儿子

后序遍历顺序为:右儿子->左儿子->父亲

 

struct Node {
    int value;
    Node *left_child;
    Node *right_child;
    Node () {
        left_child = right_child = NULL;
    }
};
bool first = true;
void Pre_order(Node *tree) {
    if(first) {
        cout << tree->value;
        first = false;
    } else cout << " " << tree->value;

    if(tree->left_child != NULL) {
        Pre_order(tree->left_child);
    }
    if(tree->right_child != NULL) {
        Pre_order(tree->right_child);
    }
}
void Mid_order(Node *tree) {
    if(tree->left_child != NULL) {
        Mid_order(tree->left_child);
    }
    if(first) {
        cout << tree->value;
        first = false;
    } else cout << " " << tree->value;
    if(tree->right_child != NULL) {
        Mid_order(tree->right_child);
    }
}
void Pos_order(Node *tree) {
    if(tree->left_child != NULL) {
        Pos_order(tree->left_child);
    }
    if(tree->right_child != NULL) {
        Pos_order(tree->right_child);
    }
    if(first) {
        cout << tree->value;
        first = false;
    } else cout << " " << tree->value;
}

 

posted on 2017-03-18 23:22  disppr  阅读(222)  评论(0编辑  收藏  举报