# 98. Validate Binary Search Tree

214人阅读 评论(0)

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.

#### 方法一：divide and conquer

bool isValidBST(TreeNode* root) {
return helper(root, INT_MIN, INT_MAX);
}
bool helper (TreeNode* t, int val_min, int val_max) {
if (t == NULL) return true;
if (t->val >= val_min && t->val <= val_max) {
if (t->left != NULL) {
if (val_min == t->val) return false;//避免二者都是INT_MIN
if (!helper(t->left, val_min, t->val-1)) return false;
}
if (t->right != NULL) {
if (val_max == t->val) return false;//避免二者都是INT_MAX
if (!helper(t->right, t->val+1, val_max)) return false;
}
return true;
}
return false;
}

#### 方法二：中序遍历二叉树inorder traverse

version 1：

bool isValidBST(TreeNode *root) {
vector<int> res;
printTree(root, res);
for (int i = 1; i < res.size(); i++) {
if (res[i] <= res[i-1]) return false;
}
return true;
}
void printTree (TreeNode *t, vector<int>& res) {
if (t == NULL) return;
if (t->left != NULL) printTree(t->left, res);
res.push_back(t->val);
if (t->right != NULL) printTree(t->right, res);
}

version 2：

class Solution {
private:
TreeNode *lastNode = NULL;
public:
bool isValidBST(TreeNode *root) {
if (root == NULL) return true;
if (!isValidBST(root->left)) return false;
if (lastNode != NULL && lastNode->val >= root->val) return false;
lastNode = root;
return (isValidBST(root->right));
}
};

个人资料
等级：
访问量： 3万+
积分： 1818
排名： 2万+
文章分类
最新评论