본문으로 바로가기
반응형

Description

이진검색트리의 root와 트리안의 최대값, 최소값이 주어졌을때 주어진 최대, 최소값을 Trim한뒤 반환해주는 문제입니다.

Given the root of a binary search tree and the lowest and highest boundaries as low and high, trim the tree so that all its elements lies in [low, high]. Trimming the tree should not change the relative structure of the elements that will remain in the tree (i.e., any node's descendant should remain a descendant). It can be proven that there is a unique answer.

Return the root of the trimmed binary search tree. Note that the root may change depending on the given bounds.

Example 1:

Input: root = [1,0,2], low = 1, high = 2
Output: [1,null,2]

Example 2:

Input: root = [3,0,4,null,2,null,null,1], low = 1, high = 3
Output: [3,2,null,1]

Constraints:

  • The number of nodes in the tree in the range [1, 10^4].
  • 0 <= Node.val <= 10^4
  • The value of each node in the tree is unique.
  • root is guaranteed to be a valid binary search tree.
  • 0 <= low <= high <= 10^4

Solution 1. DFS - Recusion

public TreeNode trimBST(TreeNode root, int low, int high) {
    if (root == null) return null;

    if (root.val < low) return trimBST(root.right, low, high);
    if (root.val > high) return trimBST(root.left, low, high);

    root.left = trimBST(root.left, low, high);
    root.right = trimBST(root.right, low, high);

    return root;
}

재귀호출을 통해 루트를 기준으로node.val > high 일경우 왼쪽에 트리밍된 이진트리가, root.val < low 일경우 오른쪽에 트리밍된 노드가 위치해야하고 그렇지 않을 경우 트리의 양쪽 노드를 잘라내어 반환합니다.

Reference

 

Trim a Binary Search Tree - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

반응형

댓글을 달아 주세요