mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 00:43:04 +08:00
JavaScript版本的《验证二叉搜索树》
This commit is contained in:
@ -377,6 +377,75 @@ func isBST(root *TreeNode, min, max int) bool {
|
||||
}
|
||||
```
|
||||
|
||||
JavaScript版本
|
||||
|
||||
> 辅助数组解决
|
||||
|
||||
```javascript
|
||||
/**
|
||||
* Definition for a binary tree node.
|
||||
* function TreeNode(val, left, right) {
|
||||
* this.val = (val===undefined ? 0 : val)
|
||||
* this.left = (left===undefined ? null : left)
|
||||
* this.right = (right===undefined ? null : right)
|
||||
* }
|
||||
*/
|
||||
/**
|
||||
* @param {TreeNode} root
|
||||
* @return {boolean}
|
||||
*/
|
||||
var isValidBST = function (root) {
|
||||
let arr = [];
|
||||
const buildArr = (root) => {
|
||||
if (root) {
|
||||
buildArr(root.left);
|
||||
arr.push(root.val);
|
||||
buildArr(root.right);
|
||||
}
|
||||
}
|
||||
buildArr(root);
|
||||
for (let i = 1; i < arr.length; ++i) {
|
||||
if (arr[i] <= arr[i - 1])
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
```
|
||||
|
||||
> 递归中解决
|
||||
|
||||
```javascript
|
||||
/**
|
||||
* Definition for a binary tree node.
|
||||
* function TreeNode(val, left, right) {
|
||||
* this.val = (val===undefined ? 0 : val)
|
||||
* this.left = (left===undefined ? null : left)
|
||||
* this.right = (right===undefined ? null : right)
|
||||
* }
|
||||
*/
|
||||
/**
|
||||
* @param {TreeNode} root
|
||||
* @return {boolean}
|
||||
*/
|
||||
let pre = null;
|
||||
var isValidBST = function (root) {
|
||||
let pre = null;
|
||||
const inOrder = (root) => {
|
||||
if (root === null)
|
||||
return true;
|
||||
let left = inOrder(root.left);
|
||||
|
||||
if (pre !== null && pre.val >= root.val)
|
||||
return false;
|
||||
pre = root;
|
||||
|
||||
let right = inOrder(root.right);
|
||||
return left && right;
|
||||
}
|
||||
return inOrder(root);
|
||||
};
|
||||
```
|
||||
|
||||
|
||||
|
||||
-----------------------
|
||||
|
Reference in New Issue
Block a user