Implementation of pre-, middle-, post-order traversal of c++ binary tree

              1
           2     3
        4   5  6  7

This article mainly implements a binary tree (c++), and realizes the pre-order traversal, in-order traversal, and subsequent traversal of the binary tree through iteration.

insert image description here

Pre-order traversal: pre_order:
1 2 4 5 3 6 7
In-order traversal: in_order:
4 2 5 1 6 3 7
Post-order traversal: post_order:
4 5 2 6 7 3 1

  • definition tree
class binaryTree {
    public:
    int value;
    binaryTree* left;
    binaryTree* right;
    binaryTree() = default;
    binaryTree(int v):value(v) {
        left = right = nullptr;
    }
    ~binaryTree() {
        delete this->left;
        delete this->right;
        left = left = nullptr;
    }
};
  • build tree
binaryTree* buildTree() {
    //           1
    //        2     3
    //     4   5  6  7
    binaryTree* d = new binaryTree(1);
    d->left = new binaryTree(2);
    d->right = new binaryTree(3);

    d->left->left = new binaryTree(4);
    d->left->right = new binaryTree(5);

    d->right->left = new binaryTree(6);
    d->right->right = new binaryTree(7);
    return d;
}
  • preorder traversal
void pre_order(const binaryTree* b) {
    if(b == nullptr) {
        return;
    }
    cout << b->value << " ";;
    pre_order(b->left);
    pre_order(b->right);
}
// output:
/*
preorder:
1 2 4 5 3 6 7 
*/
  • test code
void printTree() {
    binaryTree* b = buildTree();
    cout << "pre_order:" << endl;
    pre_order(b);
    cout << endl;

    cout << "in_order:" << endl;
    in_order(b);
    cout << endl;

    cout << "post_order:" << endl;
    post_order(b);
    cout << endl;
    return;
}

GitHub code link

Guess you like

Origin blog.csdn.net/sexyluna/article/details/126634435