Search in a Binary Search Tree - LeetCode
주어진 이진 탐색 트리 (BST)의 루트와 정수 val이 주어집니다.
BST에서 val과 값이 일치하는 노드를 찾아 해당 노드를 루트로 하는 서브 트리를 반환하거나, 그러한 노드가 존재하지 않는 경우 null을 반환하세요.
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: []
문제 요약:
주어진 이진 탐색 트리 (BST)에서 val과 값이 일치하는 노드를 찾아 해당 노드를 루트로 하는 서브 트리를 반환하거나, 그러한 노드가 존재하지 않는 경우 null을 반환하세요.
풀이과정:
class Solution {
public TreeNode searchBST(TreeNode root, int val) {
if(root == null || root.val == val) return root;
if(val < root.val){
return searchBST(root.left, val);
}else if(val > root.val) {
return searchBST(root.right, val);
}else{
return null;
}
}
}
841. Keys and Rooms (0) | 2023.10.29 |
---|---|
450. Delete Node in a BST (0) | 2023.10.29 |
1161. Maximum Level Sum of a Binary Tree (0) | 2023.10.29 |
199. Binary Tree Right Side View (0) | 2023.10.29 |
1207. Unique Number of Occurrences (0) | 2023.10.29 |