判断一棵树是否为排序二叉树(二叉搜索树)

问题:判断一棵树是否为排序二叉树(二叉搜索树)

思路:二叉排序树的中序遍历为一递增的排序,若果不满足这一条件,则,不是二叉树

程序实现:

#include <iostream>
#include<limits>

using namespace std;

typedef struct Btree
{
    int num;
    struct Btree * lchild;
    struct Btree * rchild;
} *PBtree,Btree;

int prev=numeric_limits<int>::min();

//建立一棵排序二叉树
PBtree createtree(PBtree root,int val)
{
    PBtree newNode=new Btree();
    newNode->lchild=NULL;
    newNode->rchild=NULL;
    newNode->num=val;

    if(root==NULL)
    {
        root=newNode;
        return newNode;
    }

    while(root!=NULL)
    {
        PBtree pback=NULL;
        PBtree pcur=root;
        while(pcur!=NULL)
        {
            pback=pcur;
            if(pcur->num<val)
                pcur=pcur->rchild;
            else if(pcur->num>val)
                pcur=pcur->lchild;
            else
            {
                delete newNode;
                return pcur;
            }
        }

        if(pback->num>val)
            pback->lchild=newNode;
        else
            pback->rchild=newNode;
        return pback;
    }
}

//递归实现先序遍历
void preorder(PBtree root)
{
    if(root==NULL)
        return ;
    cout<<root->num<<" ";
    preorder(root->lchild);
    preorder(root->rchild);
}

//递归实现中序遍历
void inorder(PBtree root)
{
    if(root==NULL)
        return ;
    inorder(root->lchild);
    cout<<root->num<<" ";
    inorder(root->rchild);
}

//递归实现后序遍历
void postorder(PBtree root)
{
    if(root==NULL)
        return ;
    postorder(root->lchild);
    postorder(root->rchild);
    cout<<root->num<<" ";
}



bool judgeBST1(PBtree root)
{
    if(root==NULL)
        return 1;
    else
    {
        int b=judgeBST1(root->lchild);

        if(b==0||prev>=root->num)
            return 0;
        judgeBST1(root->rchild);
    }
}
int main()
{
    PBtree root=NULL;
    //cout<<prev<<endl;
    root=createtree(root,6);
    int a[]={1,2,-6,3,-4,7,9,8,10,5};
    for(int i=0;i<10;i++)
        createtree(root,a[i]);
    cout<<judgeBST1(root)<<endl;

    inorder(root);

    return 0;
}

输出结果:

1
-6 -4 1 2 3 5 6 7 8 9 10

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值