数据结构——19 判断是否是二叉排序树

来源:互联网 发布:下载淘宝网app 编辑:程序博客网 时间:2024/05/20 18:19

二叉树——判断是否是二叉排序树


二叉树——判断是否是二叉排序树

#include<iostream>#include<queue>       //层级遍历时,用到了queue模板类#include<stack>       //前中后遍历时,用到了stack模板类using namespace std;class node            //树节点定义{public:int data;         //元素值node *parent;     //父节点node *left;       //左子节点node *right;      //右子节点public://node():data(-1),parent(NULL),left(NULL),right(NULL){};node(int num):data(num),parent(NULL),left(NULL),right(NULL){};        //构造函数,初始化类成员变量};class tree            //树定义{public:tree(int num[],int len);           //构造函数void insertNode(int data);         //安左低右高插入树的节点   bool isSortedTree();private:node *root;                        //树的根节点};tree::tree(int num[],int len)          //构造函数,插入树节点{root=new node(num[0]);for(int i=1;i<len;i++)insertNode(num[i]);}void tree::insertNode(int data){node *p,*par;node *newnode=new node(data);p=par=root;while(p){par=p;if(data > p->data)p=p->right;else if(data < p->data)p=p->left;else if(data == p->data){delete newnode;return;}}newnode->parent=par;if(par->data > newnode->data)par->left=newnode;elsepar->right=newnode;}bool tree::isSortedTree(){int lastvalue=0;stack<node *> s;node *p=root;                     //从根节点开始while(p|| !s.empty())             //树不为空或栈不为空{while(p)                      //遍历左子树,压入栈,入栈前,输出节点{s.push(p);p=p->left;}if(!s.empty()){p=s.top();s.pop();if( lastvalue==0 || lastvalue < p->data )lastvalue=p->data;else if(lastvalue >= p->data)return false;}p=p->right;}}int main(){int num[8]={5,3,7,2,4,6,8,1};tree t(num,8);cout<<t.isSortedTree();cout<<endl;return 0;}

0 0
原创粉丝点击