二叉树的基本概念:
二叉树的每个结点最多只有两个孩子结点,也就是说每个结点最多有两个子树。
二叉树有 5 种基本形态:
(1)空二叉树,树为空,没有结点;(2)只有根结点的二叉树;(3)只有左子树的二叉树;(4)只有右子树的二叉树;(5)左右子树都有的二叉树。
#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();
}
}
**//-----------中序遍历----------**
void inorder() {
if (lchild != NULL) {
lchild->inorder();
}
cout << data << " ";
if (rchild != NULL) {
rchild->inorder();
}
}
**//-----------后序遍历---------------**
void postorder() {
if (lchild != NULL) {
lchild->postorder();
}
if (rchild != NULL) {
rchild->postorder();
}
cout << data << " ";
}
};
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();
}
void inorder() {
root->inorder();
}
void postorder() {
root->postorder();
}
};
int main() {
BinaryTree binarytree;
binarytree.build_demo();
binarytree.preorder();
cout << endl;
binarytree.inorder();
cout << endl;
binarytree.postorder();
cout << endl;
return 0;
}
网友评论