[Leetcode]Validate Binary Search Tree

本文探讨了一种检查树是否为平衡二叉树的方法,分析了递归算法的局限性,并提出通过中序遍历来验证树是否为升序序列以解决此问题。这种方法的空间复杂度为O(n),有效避免了INT_MAX和INT_MIN导致的问题。

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

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.

检查一棵树是不是平衡二叉树。上边列出了BST的性质。开始写了一个递归的方法,结果问题出在了INT_MAX和INT_MIN这两个值上,如果这两个值出现在树中,这个方法就不可行了。

class Solution {
public:
	bool isValidBST(TreeNode *root) {
		return check(root, INT_MAX, INT_MIN);
	}
	bool check(TreeNode *root, int max, int min){
		if (NULL == root) return true;
		if (root->val > min && root->val < max){
			return check(root->left, root->val, min) && check(root->right, max, root->val);
		}
		else return false;
	}
};

在网上翻了好久,发现很多之前AC的代码都是这么写的,说明leetcode有可能更新了test cases,加上了对INT_MAX和INT_MIN的检测,使这些代码没办法再AC了(就像reverse integar那道题一样)。这种思路时间复杂度是O(n),空间复杂度是O(0)。

这样的话,这种思路就行不通了。只能从BST的另一个性质出发,中序遍历这棵树,如果这棵树是BST,那么这个遍历结果正好的升序排列的,这样做空间复杂度也到达了O(n)。

class Solution {
public:
	bool isValidBST(TreeNode *root) {
		vector<int> result;
		inorder(root, result);
		for (int i = 1; i < result.size(); i++){
			if (result[i - 1] >= result[i]) return false;
		}
		return true;
	}
	void inorder(TreeNode *root,vector<int> &result){
		if (!root) return;
		if (root->left) inorder(root->left, result);
		result.push_back(root->val);
		if (root->right) inorder(root->right, result);
	}
};



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值