建立排序二叉树并中序遍历

分析:中序遍历也叫中根遍历,顾名思义是把根节点放在中间来遍历,其遍历顺序为左子节点–>根节点–>右子节点。

方法一:

#include<iostream>
using namespace std;

struct node                     //二叉树结点结构
{
    int data;
    node *left;                 //右子树结点指针
    node *right;                //左子树结点指针
};

class Btree
{
    node *root;                 //根结点的指针
public:
    Btree()
     {
        root = NULL;
     }
    void CreateBtree(int);
    void Inorder()              //中序遍历主过程
     {
        Inorder(root);
        cout << endl;
     }
    void Inorder(node *);       //中序遍历子过程
};

void Btree::CreateBtree(int x)
{
    node *newnode = new node;
    newnode->data = x;
    newnode->left = NULL;
      newnode->right = NULL;

    if(NULL == root)
      {
        root = newnode;
     }
    else
    {
        node *back;
        node *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(node *root)    //中序遍历排序二叉树
{
    if(root)
    {
        Inorder(root->left);
        cout << root->data << " ";
        Inorder(root->right);
    }
}

int main()
{
    Btree A;
    int arr[]={7, 4, 1, 5, 12, 8, 13, 11};

    //排序二叉树:左子结点<根节点<右子节点
    cout << "建立排序二叉树:" << endl;
    for(int i = 0; i < 8; i++)
    {
        cout << arr[i] << " ";
        A.CreateBtree(arr[i]);
    }

    cout << endl << "中序遍历序列:" << endl;
    A.Inorder();

    return 0;
}

运行结果:

建立排序二叉树:
7 4 1 5 12 8 13 11
中序遍历序列:
1 4 5 7 8 11 12 13
Press any key to continue
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值