摘自计蒜客:http://www.jisuanke.com/course/35/1394
(一)、先序遍历
先序遍历时二叉树遍历的一种,对于每个结点,先访问当前结点,然后访问结点的左子树,最后访问结点的右子树。在子树
里依然按照这个遍历顺序访问。
#include<iostream>
using namespace std;
class Node {
public:
int data;
Node *lchild, *rchild;
Node(int _data) {
data = _data;
lchild = NULL;
rchild = NULL;
}
~Node() {
if (lchild != NULL) {
delete lchild;
}
if (rchild != NULL) {
delete rchild;
}
}
void preorder(){
cout << data << " ";
if (lchild != NULL) {
lchild->preorder();
}
if (rchild != NULL) {
rchild->preorder();
}
}
};
class BinaryTree {
private:
Node *root;
public:
BinaryTree() {
root = NULL;
}
~BinaryTree() {
if (root != NULL) {
delete root;
}
}
void build_demo() {
root = new Node(1);
root->lchild = new Node(2);
root->rchild = new Node(3);
root->lchild->lchild = new Node(4);
root->lchild->rchild = new Node(5);
root->rchild->rchild = new Node(6);
}
void preorder() {
root->preorder();
}
};
int main() {
BinaryTree binarytree;
binarytree.build_demo();
binarytree.preorder();
cout << endl;
return 0;
}
(二)、中序遍历
中序遍历和先序遍历类似,只是在遍历顺序上有所不同,中序遍历先访问当前结点的左子树,然后访问当前结点,最后访问
子树。如果左右孩子不为空,则递归调用孩子结点的中序遍历函数。
#include<iostream>
using namespace std;
class Node {
...
public:
void inorder() {
if (lchild != NULL) {
lchild->inorder();
}
cout << data << " ";
if (rchild != NULL) {
rchild->inorder();
}
}
};
class BinaryTree {
...
public:
void inorder() {
root->inorder();
}
};
(三)、后序遍历
后序遍历先访问当前结点的左子树,然后访问当前结点的右子树,最后访问当前结点。如果当前结点的左右子树不为空,则
递归调用左右孩子的后序遍历函数。
#include<iostream>
using namespace std;
class Node {
...
public:
void postorder() {
if (lchild != NULL) {
lchild->postorder();
}
if (rchild != NULL) {
rchild->postorder();
}
cout << data << " ";
}
};
class BinaryTree {
...
public:
void postorder() {
root->postorder();
}
};