반응형
SMALL
문제
Given the root of a binary tree, determine if it is a valid binary search tree (BST).
A valid BST is defined as follows:
- The left subtree of a node contains only nodes with keys less than the node's key.
- The right subtree of a node contains only nodes with keys greater than the node's key.
- Both the left and right subtrees must also be binary search trees.
Example 1:
Input: root = [2,1,3]
Output: true
Example 2:
Input: root = [5,1,4,null,null,3,6]
Output: false
Explanation: The root node's value is 5 but its right child's value is 4.
Constraints:
- The number of nodes in the tree is in the range [1, 104].
- -231 <= Node.val <= 231 - 1
코드
// DFS
var isValidBST = function(root, min = -Infinity, max = Infinity) {
// root가 없는 경우는
// 그래프가 아예 없거나, left, right 둘 다 없는 경우임
// 둘다 없을 경우 해당 root.val는 true
if(!root) return true;
// root.val은 max보다는 작아야하고
// min보다는 커야함
if(root.val >= max || root.val <= min) return false;
// left는 val보다 작고 min보다는 큼
const left = isValidBST(root.left, min, root.val);
// right는 val보다 크고 max보다는 작음
const right = isValidBST(root.right, root.val, max);
return left && right
}
반응형
LIST
'Coding Interview' 카테고리의 다른 글
[LeetCode] BFS 210. Course Schedule II (feat. 위상정렬) (0) | 2022.09.26 |
---|---|
[LeetCode] DFS 101. Symmetric Tree (0) | 2022.09.26 |
[LeetCode] DFS - 230. Kth Smallest Element in a BST (0) | 2022.09.26 |
[LeetCode] BFS 269. Alien Dictionary (1) | 2022.09.26 |
[LeetCode] DFS-BFS 124. Binary Tree Maximum Path Sum (1) | 2022.09.26 |