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.
Example 1:
2 / \ 1 3Binary tree
[2,1,3]
,
return true.
Example 2:
1 / \ 2 3Binary tree
[1,2,3]
,
return false.
解题思路:本人的思路是通过后序遍历,对于每个非叶子结点:
1.判断他们的左右子树是否是搜索二叉树
2.取回左右子树的最大最小值,判断以这个节点为根的树是否是搜索二叉树。
算法代码如下:
/**
* 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) {
int max, min;
return travel(root, min, max);
}
bool travel(TreeNode* root, int & min, int & max){
if (root == NULL) {
max = INT_MIN;
min = INT_MAX;
return true;
}
int leftMin, leftMax, rMin, rMax;
bool isBSTree = travel(root -> left, leftMin, leftMax);
if(isBSTree == false) return false;
isBSTree = travel(root -> right, rMin, rMax);
if(isBSTree == false)return false;
if(root -> left != NULL && root -> val <= leftMax) return false;
if(root -> right != NULL && root -> val >= rMin) return false;
max = leftMax > rMax ? leftMax : rMax;
max = root -> val > max ? root -> val : max;
min = leftMin < rMin ? leftMin : rMin;
min = root -> val < min ? root -> val : min;
return true;
}
};
结果如下: