您的位置:首页 > 其它

leetcode:Validate Binary Search Tree

2014-10-29 16:13 316 查看
Given a binary tree, determine if it is a valid binary search tree (BST).
Assume a BST is defined as follows:

The left subtree of a node contains only nodes with keys less than the node's key.
The right subtree of a node contains only nodes with keys greater than the node's key.
Both the left and right subtrees must also be binary search trees.

confused what
"{1,#,2,3}"
means? >
read more on how binary tree is serialized on OJ.

Show Tags

Have you met this question in a real interview?
Yes

No

题目地址:https://oj.leetcode.com/problems/validate-binary-search-tree/
解题思路:找出二叉树的中序遍历,如果出现乱序的地方就不是二叉查找树。

代码:

/**
* Definition for binary tree
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode *pre;
bool ans;
bool isValidBST(TreeNode *root) {
//中序遍历,如果得到不是顺序的地方,返回false
if(root==NULL) return true;
if(root->left==NULL&&root->right==NULL) return true;

pre=NULL;
ans=true;
inorder(root);
return ans;

}
private:
void inorder(TreeNode *root){
if(root==NULL) return;
inorder(root->left);
if(pre==NULL){
pre=root;
}
else{
if(pre->val>=root->val){
ans=false;
//找到了不是顺序的地方就直接返回,不用再继续遍历
return;
}
pre=root;
}
inorder(root->right);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: