leetcode-98-Validate Binary Search Tree

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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Example 1:

2
/ \
1 3

Input: [2,1,3]
Output: true

Example 2:

5
/ \
1 4
/ \
3 6

Input: [5,1,4,null,null,3,6]
Output: false
Explanation: The root node's value is 5 but its right child's value is 4.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
利用BST树的特性,从上往下递归,记录min_node和max_node,对左子树来说,只需记录max_node,即它的父节点;同理对于右字数,只需记录min_node。然后它们满足BST关系即可。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isValidBST(TreeNode* root) {
return root != NULL ? is_bst(root, NULL, NULL) : true;
}
bool is_bst(TreeNode* root, TreeNode* min_node, TreeNode* max_node){
if(root == NULL)
return true;
if(min_node != NULL && root->val <= min_node->val || max_node != NULL && root->val >= max_node->val)
return false; //if false, stop and return
return is_bst(root->left, min_node, root) && is_bst(root->right, root, max_node);
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
利用中序遍历关系。由于BST树的中序遍历是有序的,所以我们用中序遍历来做文章。
class Solution {
public:
bool isValidBST(TreeNode* root) {
TreeNode* prev = NULL;
return is_bst(root, prev);
}
bool is_bst(TreeNode* root, TreeNode*& prev){
if(root == NULL) return true;
if(!is_bst(root->left, prev)) return false;
if(prev != NULL && prev->val >= root->val) return false;
prev = root;
return is_bst(root->right, prev);
}
};
Donate? comment?