TreeNode 클래스는 주석 그대로 만들었음.
타겟 트리 찾는 메소드 만들어서 왼쪽, 오른쪽 재귀적으로 탐색하게 하였음.
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;
}
public TreeNode findTree(TreeNode root, int target) {
if (root == null)
{
return null;
}
if (root.val == target)
{
return new TreeNode(root.val, root.left, root.right);
}
else
{
// 왼쪽 탐색
TreeNode leftNode = findTree(root.left, target);
if (leftNode != null)
{
return leftNode;
}
// 왼쪽이 아니면 오른쪽 탐색
return findTree(root.right, target);
}
}
}
class Solution {
public TreeNode searchBST(TreeNode root, int val) {
return root.findTree(root, val);
}
}
'자율 학습 > 스터디' 카테고리의 다른 글
Binary Tree (DFS, BFS) vs. Binary Search Tree (0) | 2025.04.06 |
---|---|
[LeetCode75] Find Peak Element (0) | 2025.04.01 |
[LeetCode 75] 215. Kth Largest Element in an Array (1) | 2025.03.25 |
[LeetCode] 2352. Equal Row and Column Pairs (0) | 2025.03.18 |
[LeetCode] 2215. Find the Difference of Two Arrays (0) | 2025.03.18 |