LeetCode Validate Binary Search Tree

本文详细介绍了如何通过设置节点边界值来验证给定二叉树是否为有效的二叉搜索树(BST)。通过避免使用整数极限值,确保程序健壮性。包括递归方法的实现与解释。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 keysless thanthe node's key.
  • The right subtree of a node contains only nodes with keysgreater thanthe node's key.
  • Both the left and right subtrees must also be binary search trees.

confused what"{1,#,2,3}"means?> read more on how binary tree is serialized on OJ.

这道题就一个难点:要会设置节点的两边限制值。

吸收了LeetCode论坛上的建议,不使用INT_MAX 和INT_MIN,我这里使用了LLONG_MIN和LLONG_MAX。

因为如果是用INT_MIN,那么第一个左子树的值为INT_MIN的时候就会判断为假,其实为真。

虽然leetcode没有测试这个情况,不过健全的程序总是最好的。

class Solution {
public:
	bool isValidBST(TreeNode *root) 
	{
		return validBST(root);
	}

	//注意:别忘记了两边的boundary:leftMax和rightMax的设置
	/*
	I dont think it's a good idea to use int to represent the up and low bound of a TreeNode, INT_MIN and INT_MAX maybe used by TreeNode. We can use double or just the TreeNode itself.
	*/
	bool validBST(TreeNode *root, long long leftMax = LLONG_MIN, long long rightMax = LLONG_MAX) 
	{
		if (!root) return true;
		if (!root->left && !root->right) return true;
		if (root->left 
			&& (root->left->val >= root->val || root->left->val <= leftMax)) 
			return false;
		if (root->right 
			&& (root->right->val <= root->val || root->right->val >= rightMax )) 
			return false;

		return validBST(root->left, leftMax, root->val) 
			&& validBST(root->right, root->val, rightMax);
	}
};


//2014-2-15 update
	bool isValidBST(TreeNode *root) 
	{
		return isLegal(root);
	}
	bool isLegal(TreeNode *r, TreeNode *le = NULL, TreeNode *ri = NULL)
	{
		if (!r) return true;//||!r->left && !r->right不能增加这个条件
		if (le && le->val >= r->val || ri && ri->val <= r->val) return false;

		return isLegal(r->left, le, r) && isLegal(r->right, r, ri);
	}









评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值