二叉树遍历

二叉排序树的特点:左子树上所有的值 均小于根节点的值,右子树上的值 均大于根节点的值。左,右子树也分别为二叉排序树,按中序遍历能够得到一个递增有序序列。
也叫做二元查找树,二叉搜索树,二叉查找树...binary search tree

先序遍历:根左右
中序遍历:左根右
后续遍历:左右根

//二叉排序树(即二叉查找树)的建立。随后进行先序遍历,中序遍历和后序遍历。
#include
#include
 
using namespace std;
int n;
struct node
{
      node *lchild;
      node *rchild;
      int data;
};
void build(node *tree, int a)
{
     node*p, *q ,*f;
     p =tree;
     q =new node;
    q->data = a;
    q->lchild = NULL;
    q->rchild = NULL;
    while(p) //每次从根节点开始寻找。
    {
             f = p;
             if(p->data ==a)
             {
                      return;
             }
             if(p->data> a)
                      p = p->lchild;
             else
                p = p->rchild;
    }
    if(f->data >a)
              f->lchild =q;
    else
        f->rchild =q;
}
 
void xx(node *p1)
{
     if(p1!= NULL)
    {
          cout<< p1->data<< " ";
         xx(p1->lchild);
         xx(p1->rchild);
    }
}
void zx(node *p1)
{
     if(p1!= NULL)
    {
         zx(p1->lchild);
          cout<< p1->data<< " ";
         zx(p1->rchild);
    }
}
void hx(node *p1)
{
     if(p1!= NULL)
    {
         hx(p1->lchild);
         hx(p1->rchild);
          cout<< p1->data<< " ";
    }
}
int main(int argc, char *argv[])
{
    node *tree;
    int a;
    tree = new node;
    while(cin>> n)
    {
                   cin>> a;
                   tree->data =a;
                   tree->lchild =NULL;
                   tree->rchild =NULL;
                   for(int i = 1; i< n; i++)
                   {
                          cin>> a;
                         build(tree, a);
                   }
                   xx(tree);
                   cout<< endl;
                   zx(tree);
                   cout<< endl;
                   hx(tree);
                   cout<< endl;     
    }
    system("PAUSE");
    returnEXIT_SUCCESS;
}


//二叉搜索树的后序遍历序列
二叉搜素树:二叉排序树。数组中最后一个数既是根,向前连续寻找大于根的数字,直到小于根时停止mid,然后搜索起始点到mid,如果之间有大于根的数,则false。然后再分别在左子树和右子树中寻找。
#include <cstdlib>
#include <iostream>
using namespace std;
#define max 15000
bool check(int a[], int begin, int end)
{
    if(begin > end)
             return true;
    int mid = end-1;
    int root = a[end];
    while(a[mid] > root&& mid >=begin)
               mid--;
    
    for(int i = begin; i <= mid; i++)
            if(a[i] > root)
                    return false;
    bool left = check(a, begin, mid);
    bool right = check(a, mid+1, end-1);
    return left && right;
}

int main()
{
    int n;
    inta[max];
    while(cin>> n)
    {
       for(int i = 0; i < n; i++)
               cin >> a[i];
       if(check(a, 0, n-1))
                   cout << "Yes"<< endl;
       else
           cout << "No"<< endl;
    }
   system("pause");
    return0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值