Skip to content

Commit 1fba6b4

Browse files
committed
Solution for Validate Binary Search Tree #251
first approach second approach children solution update comments ๊ฐœํ–‰๋ฌธ์ž ์‚ฝ์ž… Update comments in validate-binary-search-tree solution for clarity
1 parent 212df12 commit 1fba6b4

1 file changed

Lines changed: 51 additions & 0 deletions

File tree

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
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+
class Solution {
17+
// TC : O(n) Each node is visited once in the loop.
18+
// SC : O(n) Memory allocated for call stack
19+
// In the first attempt, I tried BFS to solve the problem.
20+
// But I figured out that I needed to validate a BST recursively.
21+
// So, I switched to DFS to solve the problem.
22+
// At first, I compared the node's value with the children's values.
23+
// And I checked that those values were in the range of min and max.
24+
// Then, I simplified the approach by
25+
// comparing the node's value with the min and max values (assisted by ChatGPT).
26+
public boolean isValidBST(TreeNode root) {
27+
return dfs(root);
28+
}
29+
30+
// Overloading the method to set default arguments
31+
private boolean dfs(TreeNode node) {
32+
return dfs(node, Long.MIN_VALUE, Long.MAX_VALUE);
33+
}
34+
35+
private boolean dfs(TreeNode node, long min, long max) {
36+
// It's the end of the tree, return true.
37+
if (node == null) {
38+
return true;
39+
}
40+
41+
if (node.val <= min) {
42+
return false;
43+
}
44+
if (node.val >= max) {
45+
return false;
46+
}
47+
48+
// All the result of search must be true, if the tree is valid
49+
return dfs(node.left, min, node.val) && dfs(node.right, node.val, max);
50+
}
51+
}

0 commit comments

Comments
ย (0)