Skip to content

Commit a8ad6f0

Browse files
authored
[ PS ] : Validate Binary Search Tree
1 parent 25bcb9c commit a8ad6f0

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* function TreeNode(val, left, right) {
4+
* this.val = (val===undefined ? 0 : val)
5+
* this.left = (left===undefined ? null : left)
6+
* this.right = (right===undefined ? null : right)
7+
* }
8+
*/
9+
/**
10+
* ์ด์ง„ ํƒ์ƒ‰ ํŠธ๋ฆฌ(BST)์ธ์ง€ ํ™•์ธํ•˜๋Š” ํ•จ์ˆ˜
11+
* @param {TreeNode} root
12+
* @return {boolean}
13+
*/
14+
15+
///////////////////////// 1 ///////////////////////////
16+
// inorder traversalํ•œ ๊ฒฐ๊ณผ๋ฅผ ๋ฐฐ์—ด์— ๋‹ด์•„ ์˜ค๋ฆ„์ฐจ์ˆœ ์ •๋ ฌ์ธ์ง€ ํ™•์ธ
17+
const isValidBST = function(root) {
18+
const inorder = [];
19+
inorderTraversal(root, inorder);
20+
21+
return inorder.every((val, i, arr) => i === 0 || arr[i-1] < val);
22+
};
23+
24+
function inorderTraversal(current, result) {
25+
if (current.left) {
26+
inorderTraversal(current.left, result);
27+
}
28+
29+
result.push(current.val);
30+
31+
if (current.right) {
32+
inorderTraversal(current.right, result);
33+
}
34+
}
35+
36+
///////////////////////// 2 ///////////////////////////
37+
// inorder traversalํ•˜๋ฉด์„œ ๋ฐ”๋กœ ์ง์ „์— ์ˆœํšŒํ•œ ๊ฐ’์ด ํ˜„์žฌ ๊ฐ’๋ณด๋‹ค ์ž‘์€์ง€ ํ™•์ธ (=์˜ค๋ฆ„์ฐจ์ˆœ์ธ์ง€ ๋ฐ”๋กœ๋ฐ”๋กœ ํ™•์ธ)
38+
const isValidBST = function(root) {
39+
let prev = -Infinity;
40+
41+
function inorder(node) {
42+
if (!node) return true;
43+
44+
if (!inorder(node.left)) return false;
45+
46+
if (node.val <= prev) return false;
47+
prev = node.val;
48+
49+
return inorder(node.right);
50+
}
51+
52+
return inorder(root);
53+
};
54+
55+
// ์‹œ๊ฐ„๋ณต์žก๋„: O(n)
56+
// ๊ณต๊ฐ„๋ณต์žก๋„: O(n) (์žฌ๊ท€ ์Šคํƒ == ํŠธ๋ฆฌ ๋†’์ด. ์ตœ์•…์˜ ๊ฒฝ์šฐ ํŽธํ–ฅ ํŠธ๋ฆฌ์ผ ๋•Œ ๋†’์ด๋Š” n)

0 commit comments

Comments
ย (0)