careercup-树与图 4.5

时间:2024-08-13 09:05:56

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

参考:http://blog.****.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[]= {,,,,,,,,,};
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;
}