Skip to content

Commit

Permalink
feat: 98.validate-binary-search-tree 增加定义法 (#331)
Browse files Browse the repository at this point in the history
* Update 98.validate-binary-search-tree.md

validate-binary-search-tree 定义法添加js代码实现

* Update 98.validate-binary-search-tree.md

* Update problems/98.validate-binary-search-tree.md

Co-Authored-By: lucifer <azl397985856@gmail.com>

* Update 98.validate-binary-search-tree.md

格式化

Co-authored-by: lucifer <azl397985856@gmail.com>
  • Loading branch information
TH-coder and azl397985856 committed Apr 1, 2020
1 parent 87cda1a commit e77854d
Showing 1 changed file with 31 additions and 3 deletions.
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)

0 comments on commit e77854d

Please sign in to comment.