首页 > 代码库 > 二叉树建立,遍历和二叉排序树的判断【c++】

二叉树建立,遍历和二叉排序树的判断【c++】

// test.cpp : Defines the entry point for the console application.//#include "stdafx.h"#include <iostream>using namespace std;typedef struct BTree{    char val;    struct BTree *lchild,*rchild;}BTree;//先序建立二叉树BTree * CreateBTree(BTree *T)  {      char value;     cin >> value;      if(# == value)          T = NULL;      else      {          T = new BTree;          T->val = value;          cout<<"left of "<<T->val<<" :"<<endl;        T->lchild=CreateBTree(T->lchild);          cout<<"right of "<<T->val<<" :"<<endl;        T->rchild=CreateBTree(T->rchild);      }    return T;}   
/*建立二叉排序树*/BTree
* insertNode(BTree *Root,int value){ BTree* p=new BTree(); p->val=value; p->lchild=NULL; p->rchild=NULL; if(Root==NULL) { Root=p; return Root; } if(value<=Root->val) Root->lchild=insertNode(Root->lchild,value); else if(value>Root->val) Root->rchild=insertNode(Root->rchild,value); return Root; }//先序遍历二叉树void PreOrderTraverse(BTree* T){ if(T){ printf("%c ",T->val); PreOrderTraverse(T->lchild); PreOrderTraverse(T->rchild); }}//中序遍历void InOrderTraverse(BTree* T){ if(T){ InOrderTraverse(T->lchild); printf("%c ",T->val); InOrderTraverse(T->rchild); }}//后序遍历void PostOrderTraverse(BTree* T){ if(T){ PostOrderTraverse(T->lchild); PostOrderTraverse(T->rchild); printf("%c ",T->val); }}
//递归遍历二叉树是否为二叉排序树
int IsSearchTree(BTree *t) { if(!t) //空二叉树情况 return 1; else if(!(t->lchild) && !(t->rchild)) //左右子树都无情况 return 1; else if((t->lchild) && !(t->rchild)) //只有左子树情况 { if(t->lchild->val>t->val) return 0; else return IsSearchTree(t->lchild); } else if((t->rchild) && !(t->lchild)) //只有右子树情况 { if(t->rchild->val<t->val) return 0; else return IsSearchTree(t->rchild); } else //左右子树全有情况 { if((t->lchild->val>t->val) || (t->rchild->val<t->val)) return 0; else return ( IsSearchTree(t->lchild) && IsSearchTree(t->rchild) ); }}/*写法复杂,但代码少的判断二叉排序树的方法*/int Prev=INT_MIN;int JudgeBST(BTree *t){ int b1,b2; if (t==NULL) return 1; else{ b1=JudgeBST(t->lchild); if (b1==0||Prev>=t->val) return 0; Prev=t->val; b2=JudgeBST(t->rchild); return b2; }}int main(int argc, char* argv[]){ /*建立*/ BTree *root=new BTree(); printf("creating a binary tree with root:\n"); root=CreateBTree(root); /*输出*/ PreOrderTraverse(root); printf("\n"); InOrderTraverse(root); printf("\n"); PostOrderTraverse(root); printf("\n"); /*是否排序树*/ printf("%d\n",IsSearchTree(root)); printf("%d\n",JudgeBST(root)); system("pause"); return 0;}

 二叉排序树即中序遍历结果为递增的二叉树,如:

技术分享

二叉树建立,遍历和二叉排序树的判断【c++】