您的位置:首页 > 其它

检查是否为BST

2016-08-12 00:00 141 查看
请实现一个函数,检查一棵二叉树是否为二叉查找树。给定树的根结点指针TreeNode* root,请返回一个bool,代表该树是否为二叉查找树。

一般可以有两种,都贴出来:

/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/

class Checker {
public:
bool checkBST(TreeNode* root) {
return checkBST(root, INT_MIN, INT_MAX);
}
bool checkBST(TreeNode* root, int leftVal, int rightVal){
if(root->val > leftVal && root->val < rightVal){
if(root->left){
if(!checkBST(root->left, leftVal, root->val))
return false;
}
if(root->right){
if(!checkBST(root->right,root->val, rightVal))
return false;
}
return true;
}
return false;
}
};

第二种,这种比较抽象,需要再思考一下

TreeNode* pre = NULL;
bool checkBST(TreeNode* root) {
if(Inorder(root)!=NULL) return false;
return true;
}
TreeNode* Inorder(TreeNode *root) {
if(root==NULL) return NULL;
TreeNode* left=Inorder(root->left);
if(left!=NULL) return left;
if(pre!=NULL&&pre->val>root->val) return root;
pre = root;
TreeNode *right=Inorder(root->right);
if(right!=NULL) return right;
return NULL;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法