Skip to content

Commit 67c5aa6

Browse files
committed
feat: validate-binary-search-tree solve
1 parent 000b4f0 commit 67c5aa6

File tree

1 file changed

+86
-0
lines changed

1 file changed

+86
-0
lines changed
Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* public class TreeNode {
4+
* int val;
5+
* TreeNode left;
6+
* TreeNode right;
7+
* TreeNode() {}
8+
* TreeNode(int val) { this.val = val; }
9+
* TreeNode(int val, TreeNode left, TreeNode right) {
10+
* this.val = val;
11+
* this.left = left;
12+
* this.right = right;
13+
* }
14+
* }
15+
*/
16+
/***
17+
* dfs๋กœ ๋‚ด๋ ค๊ฐ€๋ฉด์„œ node์™€ ์ž๋…€ ๋…ธ๋“œ์˜ ๊ฐ’์„ ๋น„๊ตํ•˜๊ธฐ
18+
* ๋‹ค๋งŒ, ์ž๋…€๋…ธ๋“œ๋Š” ์ฃผ์–ด์ง„ ๋ฒ”์œ„ ๋‚ด์— ์žˆ์–ด์•ผํ•œ๋‹ค.
19+
* sml < childNpde < lrg
20+
*
21+
*/
22+
class Solution {
23+
public boolean isValidBST(TreeNode root) {
24+
return dfs(root, null, null);
25+
}
26+
27+
/**
28+
* 1. node์˜ ์ž๋…€ ๋…ธ๋“œ๋Š” sml <= val <= lrg๋ฅผ ํ•ญ์ƒ ๋งŒ์กฑํ•ด์•ผํ•œ๋‹ค.
29+
* 2. sml, lrg๊ฐ€ null์ด๋ฉด ์ƒ๊ด€ ์—†์Œ
30+
* 3. node์˜ val๊ณผ๋„ ๋งž๊ฒŒ ์œ ์ง€ํ•ด์•ผํ•œ๋‹ค.
31+
*
32+
* Runtime: 0 ms (Beats 100.00%)
33+
* Memory: 45.1 MB (Beats 13.09%)
34+
* Space Complexity: O(N)
35+
* - ์ด ๋…ธ๋“œ์˜ ๊ฐœ์ˆ˜๋ฅผ N์ด๋ผ๊ณ  ํ•  ๋•Œ, dfs๋กœ ๋ชจ๋“  ๋…ธ๋“œ ์ˆ˜๋งŒํผ ์Šคํƒ์„ ์Œ“๊ธฐ ๋•Œ๋ฌธ์—
36+
* > O(N)
37+
* Time Complexity: O(N)
38+
* - dfs๋กœ ๋ชจ๋“  ๋…ธ๋“œ๋ฅผ 1ํšŒ ํƒ์ƒ‰ O(N)
39+
* > O(N)
40+
*/
41+
private boolean dfs(TreeNode node, Integer sml, Integer lrg) {
42+
TreeNode lN = node.left;
43+
TreeNode rN = node.right;
44+
boolean rslt = true;
45+
// System.out.println("node.val->"+node.val+" sml->"+sml+" lrg->"+lrg+"====IN");
46+
if (lN != null) {
47+
// 1. ๋ฒ”์œ„ ์ฒดํฌ
48+
if ((sml != null && sml >= lN.val)
49+
|| (lrg != null && lrg <= lN.val)) {
50+
return false;
51+
}
52+
53+
// 2. node์™€ left ์ž๋…€ ๊ฐ’ ๋น„๊ต
54+
if (node.val <= lN.val) {
55+
return false;
56+
}
57+
// System.out.println(". lN->"+lN.val);
58+
// 3. ๋ฒ”์œ„ ์ง€์ •. ์•ž์œผ๋กœ ๋ชจ๋“  ๋…ธ๋“œ๋Š” node.val ๋ณด๋‹ค ์ž‘์•„์•ผํ•œ๋‹ค.
59+
rslt = dfs(lN, sml, node.val);
60+
if (!rslt) {
61+
return rslt;
62+
}
63+
}
64+
65+
if (rN != null) {
66+
// 1. ๋ฒ”์œ„ ์ฒดํฌ
67+
if ((sml != null && sml >= rN.val)
68+
|| (lrg != null && lrg <= rN.val)) {
69+
return false;
70+
}
71+
// 2. node์™€ left ์ž๋…€ ๊ฐ’ ๋น„๊ต
72+
if (node.val >= rN.val) {
73+
return false;
74+
}
75+
// System.out.println(". rN->"+rN.val);
76+
// 3. ๋ฒ”์œ„ ์ง€์ •. ์•ž์œผ๋กœ ๋ชจ๋“  ๋…ธ๋“œ๋Š” node.val ๋ณด๋‹ค ์ปค์•ผํ•œ๋‹ค.
77+
rslt = dfs(rN, node.val, lrg);
78+
if (!rslt) {
79+
return rslt;
80+
}
81+
}
82+
// System.out.println("node.val->"+node.val+" sml->"+sml+"
83+
// lrg->"+lrg+"====OUT");
84+
return rslt;
85+
}
86+
}

0 commit comments

Comments
ย (0)