【LeetCode】98. Validate Binary Search Tree(C++)

地址:https://leetcode.com/problems/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.
    Example 1:
    在这里插入图片描述

Example 2:
在这里插入图片描述

理解:

判断一个树是不是二叉排序树。

实现1:

采用中序遍历的方式,得到的应该是一个有序序列,如果其中存在无序元素,就把标记修改,最后返回标记。

class Solution {
	TreeNode* pre = nullptr;
	bool valid = true;
public:
	bool isValidBST(TreeNode* root) {
		isValid(root);
		return valid;
	}

	void isValid(TreeNode* root) {
		if (!root) return;
		isValid(root->left);
		if (pre&&pre->val >= root->val) valid = false;
		pre = root;
		isValid(root->right);
	}
};

实现2:

看了下别人的实现,使用从上到下的方式,标记这个结点上面的最大值和最小值,一旦不满足就返回false,这样比较快。

class Solution {
public:
	bool isBalanced(TreeNode* curr, long minVal, long maxVal) {
		if (!curr) return true;
		long currVal = static_cast<long>(curr->val);
		if (currVal > maxVal || currVal < minVal) return false;
		return (isBalanced(curr->left, minVal, currVal - 1) &&
			isBalanced(curr->right, currVal + 1, maxVal));
	}


	bool isValidBST(TreeNode* root) {
		return isBalanced(root, LONG_MIN, LONG_MAX);
	}
};

猜你喜欢

转载自blog.csdn.net/Ethan95/article/details/85030190