Skip to content

Commit 4e82462

Browse files
committed
feat(soobing): week2 > validate-binary-search-tree
1 parent 7882a55 commit 4e82462

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
/**
2+
* ๋ฌธ์ œ ์œ ํ˜•
3+
* - Tree
4+
*
5+
* ๋ฌธ์ œ ์„ค๋ช…
6+
* - ์ด์ง„ ํƒ์ƒ‰ ํŠธ๋ฆฌ๊ฐ€ ๋งž๋Š”์ง€ ํ™•์ธํ•˜๊ธฐ
7+
*
8+
* ์•„์ด๋””์–ด
9+
* 1) ์ค‘์œ„ ์ˆœํšŒ ํ›„ ์ •๋ ฌ๋œ ๋ฐฐ์—ด์ธ์ง€ ํ™•์ธ
10+
*
11+
*/
12+
class TreeNode {
13+
val: number;
14+
left: TreeNode | null;
15+
right: TreeNode | null;
16+
constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
17+
this.val = val === undefined ? 0 : val;
18+
this.left = left === undefined ? null : left;
19+
this.right = right === undefined ? null : right;
20+
}
21+
}
22+
23+
function isSorted(arr: number[]) {
24+
for (let i = 1; i < arr.length; i++) {
25+
if (arr[i - 1] >= arr[i]) return false;
26+
}
27+
return true;
28+
}
29+
function inorder(node: TreeNode | null, arr: number[]) {
30+
if (node === null) return;
31+
inorder(node.left, arr);
32+
arr.push(node.val);
33+
inorder(node.right, arr);
34+
}
35+
function isValidBST(root: TreeNode | null): boolean {
36+
const sortedArray: number[] = [];
37+
inorder(root, sortedArray);
38+
return isSorted(sortedArray);
39+
}

0 commit comments

Comments
ย (0)