思路:

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);
	}	
};

  

相关文章:

  • 2021-11-19
  • 2021-06-05
  • 2021-11-18
  • 2021-12-11
  • 2022-01-16
猜你喜欢
  • 2022-01-28
  • 2021-11-29
  • 2022-02-24
  • 2021-09-27
  • 2022-01-09
  • 2021-07-30
相关资源
相似解决方案