/*-------------------------------------------------------------
::一般情况下,二叉树中左边节点的数值要小于右边
中序遍历 按 左子树 根节点 右子树的顺序遍历。
先序遍历 按 根节点 左子树 右子树的顺序遍历。
后序遍历 按 左子树 右子树 根节点的顺序遍历
比如 6
/ \ 中序: 1 4 5 6 7
4 7
/ \ 先序: 6 4 1 5 7
1 5
后序: 1 5 4 7 6
**程序功能:建立一个排序二叉树,并给出中序遍历该二叉树的结果
---------------------------------------------------------------*/
#include <iostream>
using namespace std;
struct tree//定义二叉树节点结构
{
int data;
tree *right, *left;//左、右子树指针
};
class Btree
{
tree *root;//树根节点的指针
public:
Btree() { root = NULL; }
void create_btree(int);//建立排序二叉树
void display() { inorder(root); cout << endl; }//传入根节点指针,中序遍历输出显示
void inorder(tree *);//调用递归中序遍历
};
void Btree::create_btree(int x)
{
tree *newnode = new tree;
newnode -> data = x;
newnode -> right = newnode -> left = NULL;
if (root == NULL)
root = newnode; //第一个创建的树为树根
else
{
tree *back;
tree *current = root;
while (current != NULL)//找到可以插入newnode的指针
{
back = current;
if (current -> data > x)//新数据小于当前数据则往左边寻找
current = current -> left;
else
current = current -> right;
}
if (back -> data > x)//找到插入指针后在判断具体插哪边,小的在左边
back -> left = newnode;
else
back -> right = newnode;
}
}
void Btree::inorder(tree *tmp)
{
if (tmp != NULL)
{
inorder(tmp -> left);//先递归到左端的节点,即tmp为NULL时输出数值
cout << tmp -> data << " ";
inorder(tmp -> right);//判断右边是否到了端点
}
}
void main()
{
Btree A;
int arr[] = {7,4,1,5,12,8,13,11,56,43,667,33,67,68,34,89,34535,46452,69,3};
cout << "建立排序二叉树顺序:" << endl;
for (int i = 0; i < 20; i++)
{
cout << arr[i] << " ";
A.create_btree(arr[i]);
}
A.create_btree(13);
A.create_btree(1300);
cout << endl << "中序遍历序列:" << endl;
A.display();
}