[Leetcode #700] Search in a Binary Search Tree

Seongyeol Shin·2022년 4월 14일
0

leetcode

목록 보기
179/196
post-thumbnail

Problem

You are given the root of a binary search tree (BST) and an integer val.

Find the node in the BST that the node's value equals val and return the subtree rooted with that node. If such a node does not exist, return null.

Example 1:

Input: root = [4,2,7,1,3], val = 2
Output: [2,1,3]

Example 2:

Input: root = [4,2,7,1,3], val = 5
Output: []

Constraints:

· The number of nodes in the tree is in the range [1, 5000].
· 1 <= Node.val <= 10⁷
· root is a binary search tree.
· 1 <= val <= 10⁷

Idea

BST이므로 주어진 값이 현재 노드보다 크면 오른쪽 노드를, 작으면 왼쪽 노드를 탐색하면 된다. 일치하는 값이 나오거나 null이 나올 경우 해당 노드를 리턴하면 된다.

Solution

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public TreeNode searchBST(TreeNode root, int val) {
        return findNode(root, val);
    }

    private TreeNode findNode(TreeNode node, int val) {
        if (node == null || node.val == val) {
            return node;
        }

        if (node.val > val) {
            return findNode(node.left, val);
        } else {
            return findNode(node.right, val);
        }
    }
}

Reference

https://leetcode.com/problems/search-in-a-binary-search-tree/

profile
서버개발자 토모입니다

0개의 댓글