-
Notifications
You must be signed in to change notification settings - Fork 3
/
solution-bfs.ts
47 lines (38 loc) · 885 Bytes
/
solution-bfs.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/*
* @lc app=leetcode id=700 lang=javascript
*
* [700] Search in a Binary Search Tree
*/
// @lc code=start
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
interface TreeNode {
val: number;
left: TreeNode | null;
right: TreeNode | null;
}
/**
* @param {TreeNode} root
* @param {number} val
* @return {TreeNode}
*/
const searchBST = (root: TreeNode | null, val: number): TreeNode | null => {
// * ['72 ms', '92.19 %', '42.7 MB', '6.25 %']
if (root === null) return null;
const queue: TreeNode[] = [root];
let cur: TreeNode | null = null;
while (queue.length) {
cur = queue.shift()!;
if (cur.val === val) return cur;
cur.left && queue.push(cur.left);
cur.right && queue.push(cur.right);
}
return null;
};
// @lc code=end
export { searchBST };