mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 00:43:04 +08:00
Merge pull request #1105 from xiaofei-2020/tree24
添加(0098.验证二叉搜索树.md):增加typescript版本
This commit is contained in:
@ -526,6 +526,48 @@ var isValidBST = function (root) {
|
||||
};
|
||||
```
|
||||
|
||||
## TypeScript
|
||||
|
||||
> 辅助数组解决:
|
||||
|
||||
```typescript
|
||||
function isValidBST(root: TreeNode | null): boolean {
|
||||
const traversalArr: number[] = [];
|
||||
function inorderTraverse(root: TreeNode | null): void {
|
||||
if (root === null) return;
|
||||
inorderTraverse(root.left);
|
||||
traversalArr.push(root.val);
|
||||
inorderTraverse(root.right);
|
||||
}
|
||||
inorderTraverse(root);
|
||||
for (let i = 0, length = traversalArr.length; i < length - 1; i++) {
|
||||
if (traversalArr[i] >= traversalArr[i + 1]) return false;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
```
|
||||
|
||||
> 递归中解决:
|
||||
|
||||
```typescript
|
||||
function isValidBST(root: TreeNode | null): boolean {
|
||||
let maxVal = -Infinity;
|
||||
function inorderTraverse(root: TreeNode | null): boolean {
|
||||
if (root === null) return true;
|
||||
let leftValid: boolean = inorderTraverse(root.left);
|
||||
if (!leftValid) return false;
|
||||
if (maxVal < root.val) {
|
||||
maxVal = root.val
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
let rightValid: boolean = inorderTraverse(root.right);
|
||||
return leftValid && rightValid;
|
||||
}
|
||||
return inorderTraverse(root);
|
||||
};
|
||||
```
|
||||
|
||||
|
||||
|
||||
-----------------------
|
||||
|
Reference in New Issue
Block a user