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.

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

解答:

根据二叉查找树的定义:

  • 结点node的左子树所有结点的值都小于node的值。
  • 结点node的右子树所有结点的值都大于node的值。
  • 结点node的左右子树同样都必须是二叉搜索树。
采用递归判断,在判断一个二叉树是否是二叉查找树的同时,需要返回该二叉查找树的最大和最小值,用于父节点判断。
参考:在判断一个树是否是平衡二叉树时返回二叉树的深度。(链接

如果该节点为空 那么直接返回 true。
如果该节点是叶子节点,返回 true, 该树的最大值和最小值都是node->val.
如果该节点的两个左右子树都是二叉查找树。
{
如果左子树为空,同时节点值小于右子树最小值。 是二叉查找树,更新Max = rightmax , min = node->val;
如果右子树为空,同时节点值大于左子树最大值。 是二叉查找树,更新max = node->val, min = leftmin;
如果左右子树都不为空,同时节点值大于左子树最大值,小于右子树最小值,是二叉树。更新max = rightmax, min = leftmin;
}
另外的几种解法:链接
还有一种中序遍历法没看懂,再看。
代码:

class Solution {
public:
    bool isValidBST(TreeNode *root) {
        int max, min;
		return isBST(root, max, min);
    }
	bool isBST(TreeNode *node, int &max, int &min)
	{
		int leftmax;
		int leftmin;
		int rightmax;
		int rightmin;
		if(node == NULL)
			return true;
		if(node->left == NULL && node->right == NULL)
		{
			max = node->val;
			min = node->val;
			return true;
		}
		else if(isBST(node->left, leftmax, leftmin) && isBST(node->right, rightmax, rightmin))
		{
			if(node->left == NULL && node->val < rightmin)
			{
				max = rightmax;
				min = node->val;
				return true;
			}
			else if(node->right == NULL && node->val > leftmax)
			{
				max = node->val;
				min = leftmin;
				return true;
			}
			else if(leftmax < node->val && node->val < rightmin)
			{
				max = rightmax;
				min = leftmin;
				return true;
			}
			
			return false;
		}
		else
		{
			return false;
		}
	}
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值