Leetcode: Validate Binary Search Tree

思路:

1. 难点在于构造递归函数的参数

2. 参数要包含上下界, 才能具有全局性. 第一次提交 WA 了, 因为写成来的判断函数是局部性的

代码:

const int POS = 1E9;
const int NEG = -1E9;
class Solution {
public:
	bool ans;
    bool isValidBST(TreeNode *root) {
		if(root == NULL)
			return true;

		ans = true;
		if(root->left) 
			isBST(root->left, NEG, root->val);
		if(root->right)
			isBST(root->right, root->val, POS);
		return ans;
    }
	void isBST(TreeNode *root, const int &minval, const int &maxval) {
		if(root->val >= maxval || root->val <= minval)
			ans = false;
		if(root->left && ans) {
			isBST(root->left, minval, root->val);
		}
		if(root->right && ans)
			isBST(root->right, root->val, maxval);
	}	
};

  

原文地址:https://www.cnblogs.com/xinsheng/p/3468240.html