首页 > 代码库 > careercup-树与图 4.5

careercup-树与图 4.5

4.5 实现一个函数,检查一棵二叉树是否为二叉查找树。

参考:http://blog.csdn.net/sgbfblog/article/details/7771096

 

C++实现代码:

#include<iostream>#include<new>#include<climits>using namespace std;struct TreeNode{    int val;    TreeNode *left;    TreeNode *right;    TreeNode(int x) : val(x), left(NULL), right(NULL) {}};void insert(TreeNode *&root,int key){        if(root==NULL)            root=new TreeNode(key);        else if(key<root->val)            insert(root->left,key);        else            insert(root->right,key);}void creatBST(TreeNode *&root){    int arr[10]= {29,4,6,1,8,3,0,78,23,89};    for(auto a:arr)        insert(root,a);}bool ishelper(TreeNode *root,int min,int max){    if(root==NULL)        return true;    if(root->val<=min||root->val>=max)        return false;    return ishelper(root->left,min,root->val)&&ishelper(root->right,root->val,max);}bool isBST(TreeNode *root){    return ishelper(root,INT_MIN,INT_MAX);}void inorder(TreeNode *root){    if(root)    {        inorder(root->left);        cout<<root->val<<" ";        inorder(root->right);    }}int main(){    TreeNode *root=NULL;    creatBST(root);    inorder(root);    cout<<endl;    cout<<isBST(root)<<endl;}

 

careercup-树与图 4.5