티스토리 뷰
Problem
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, 10^4].
- -2^31 <= Node.val <= 2^31 - 1
Solution
이진 트리의 루트 노드가 주어질 때 유효한 이진 탐색 트리인지 확인하는 문제입니다.
이진 탐색 트리(BST)는 다음과 같이 정의됩니다.
노드의 왼쪽 하위 트리에는 노드 키보다 작은 키가 있는 노드만 포함됩니다. 노드의 오른쪽 하위 트리에는 노드 키보다 큰 키가 있는 노드만 포함됩니다. 왼쪽 및 오른쪽 하위 트리도 모두 이진 검색 트리여야 합니다.
import io.lcalmsky.leetcode.TreeNode;
public class Solution {
public boolean isValidBST(TreeNode root) {
return isValidBST(root, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY);
}
private boolean isValidBST(TreeNode node, double min, double max) {
if (node == null) {
return true;
}
if (node.val <= min || node.val >= max) {
return false;
}
return isValidBST(node.left, min, node.val) && isValidBST(node.right, node.val, max);
}
}
재귀호출로 각 노드를 탐색하면서 BST 조건에 부합하는지 확인합니다.
Test
package io.lcalmsky.leetcode.validate_binary_search_tree;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import io.lcalmsky.leetcode.TreeNode;
import org.junit.jupiter.api.Test;
class SolutionTest {
@Test
public void givenTreeNode_whenValidate_thenCorrect() {
assertAll(() -> test(TreeNode.of(2, 1, 3), true), () -> test(TreeNode.of(5, 1, 4, null, null, 3, 6), false),
() -> test(TreeNode.of(10, 5, 15, null, null, 6, 20), false));
}
private void test(TreeNode given, boolean expected) {
// when
Solution validateBinarySearchTree = new Solution();
boolean actual = validateBinarySearchTree.isValidBST(given);
// then
assertEquals(expected, actual);
}
}
'Algorithm > LeetCode' 카테고리의 다른 글
13. Roman to Integer (0) | 2022.08.13 |
---|---|
235. Lowest Common Ancestor of a Binary Search Tree (0) | 2022.08.12 |
377. Combination Sum IV (0) | 2022.08.06 |
729. My Calendar I (0) | 2022.08.05 |
890. Find and Replace Pattern (0) | 2022.07.30 |
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- JPA
- 스프링 부트
- 함께 자라기 후기
- Spring Boot Tutorial
- QueryDSL
- spring boot jwt
- 스프링 부트 회원 가입
- 스프링 부트 튜토리얼
- @ManyToOne
- gRPC
- 헥사고날 아키텍처
- Spring Data JPA
- JSON
- 클린 아키텍처
- 알고리즘
- 스프링 데이터 jpa
- proto3
- Linux
- leetcode
- 스프링부트
- r
- Spring Boot
- Java
- 스프링 부트 애플리케이션
- intellij
- 함께 자라기
- spring boot application
- Spring Boot JPA
- spring boot app
- Jackson
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
글 보관함