Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: 98.validate-binary-search-tree 增加定义法 #331

Merged
merged 4 commits into from
Apr 1, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 31 additions & 3 deletions problems/98.validate-binary-search-tree.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ Explanation: The root node's value is 5 but its right child's value is 4.
我们只需要中序遍历,然后两两判断是否有逆序的元素对即可,如果有,则不是BST,否则即为一个BST。

### 定义法
根据定义,一个结点若是在根的左子树上,那它应该小于根结点的值而大于左子树最大值;若是在根的右子树上,那它应该大于根结点的值而小于右子树最小值。也就是说,每一个结点必须落在某个取值范围:
根据定义,一个结点若是在根的左子树上,那它应该小于根结点的值而大于左子树最小值;若是在根的右子树上,那它应该大于根结点的值而小于右子树最大值。也就是说,每一个结点必须落在某个取值范围:
1. 根结点的取值范围为(考虑某个结点为最大或最小整数的情况):(long_min, long_max)
2. 左子树的取值范围为:(current_min, root.value)
3. 右子树的取值范围为:(root.value, current_max)
Expand Down Expand Up @@ -151,7 +151,7 @@ public:
};
```

Java Implementation
Java Code:

```java
/**
Expand Down Expand Up @@ -185,7 +185,7 @@ class Solution {

### 定义法

* 语言支持:C++,Python3, Java
* 语言支持:C++,Python3, Java, JS

C++ Code:

Expand Down Expand Up @@ -311,6 +311,34 @@ class Solution {
}
```

JavaScript Code:

```javascript
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {boolean}
*/
var isValidBST = function (root) {
if (!root) return true;
return valid(root);
};

function valid(root, min = -Infinity, max = Infinity) {
if (!root) return true;
const val = root.val;
if (val <= min) return false;
if (val >= max) return false;
return valid(root.left, min, val) && valid(root.right, val, max)
}
```

## 相关题目

[230.kth-smallest-element-in-a-bst](./230.kth-smallest-element-in-a-bst.md)