mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
Merge pull request #1103 from xiaofei-2020/tree23
添加(0700.二叉搜索树中的搜索.md):增加typescript版本
This commit is contained in:
@ -334,6 +334,36 @@ var searchBST = function (root, val) {
|
|||||||
};
|
};
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## TypeScript
|
||||||
|
|
||||||
|
> 递归法
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
function searchBST(root: TreeNode | null, val: number): TreeNode | null {
|
||||||
|
if (root === null || root.val === val) return root;
|
||||||
|
if (root.val < val) return searchBST(root.right, val);
|
||||||
|
if (root.val > val) return searchBST(root.left, val);
|
||||||
|
return null;
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
> 迭代法
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
function searchBST(root: TreeNode | null, val: number): TreeNode | null {
|
||||||
|
let resNode: TreeNode | null = root;
|
||||||
|
while (resNode !== null) {
|
||||||
|
if (resNode.val === val) return resNode;
|
||||||
|
if (resNode.val < val) {
|
||||||
|
resNode = resNode.right;
|
||||||
|
} else {
|
||||||
|
resNode = resNode.left;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
-----------------------
|
-----------------------
|
||||||
|
Reference in New Issue
Block a user