二叉树操作类

/*-------------------------------------------------------------
::一般情况下,二叉树中左边节点的数值要小于右边
中序遍历 按  左子树  根节点  右子树的顺序遍历。
先序遍历 按  根节点  左子树  右子树的顺序遍历。
后序遍历 按  左子树  右子树  根节点的顺序遍历
比如 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();
}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

东皇※太一

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值