https://leetcode.com/problems/search-in-a-binary-search-tree/description
Search in a Binary Search Tree - LeetCode
Can you solve this real interview question? Search in a Binary Search Tree - 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
leetcode.com
Q. 주어진 Binary Tree에서 해당 값을 가진 노드를 찾아서 반환하라.
Solution.
2진 트리 탐색의 기본을 알고 적용하는 문제.
재귀 탐색
TreeNode* searchBST(TreeNode* node, int val)
{
if (node == NULL) return NULL;
if (node->val < val) return searchBST(node->right, val);
if (node->val > val) return searchBST(node->left, val);
return node;
}
Loop 탐색
TreeNode* searchBST(TreeNode* node, int val)
{
while(node)
{
if (node->val < val) node = node->right;
else if (node->val > val) node = node->left;
else break;
}
return node;
}
속도가 느리게 처리되는 것이 다소 아쉽긴 하지만,
속도가 빠른 쪽의 알고리즘 풀이를 보아도, 딱히 어떤 특별 해법에 기인한 것들은 아니라 이대로 keep.
'Leetcode > LeetCode75' 카테고리의 다른 글
[Heap/Priority Queue][Medium] 215. Kth Largest Element in an Array (1) | 2024.01.02 |
---|---|
[Binary Search Tree][Medium] 450. Delete Node in a BST (1) | 2023.12.31 |
[Binary Tree-BFS][Medium] 1161. Maximum Level Sum of a Binary Tree (1) | 2023.12.28 |
[Binary Tree-BFS][Medium] 199. Binary Tree Right Side View (1) | 2023.12.28 |
[Binary Tree-DFS][Medium] 236. Lowest Common Ancestor of a Binary Tree (1) | 2023.12.27 |