前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >建立排序二叉树并中序遍历

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

作者头像
全栈程序员站长
发布2022-09-15 10:26:24
1910
发布2022-09-15 10:26:24
举报
文章被收录于专栏:全栈程序员必看

大家好,又见面了,我是你们的朋友全栈君。

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

方法一:

代码语言:javascript
复制
#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; }

运行结果:

代码语言:javascript
复制
建立排序二叉树:
7 4 1 5 12 8 13 11
中序遍历序列:
1 4 5 7 8 11 12 13
Press any key to continue

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/160031.html原文链接:https://javaforall.cn

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档