[leetcode] #DFS 1379. Find a Corresponding Node of a Binary Tree in a Clone of That Tree

bien·2024년 5월 31일
0

코딩테스트

목록 보기
10/14

문제

1379. Find a Corresponding Node of a Binary Tree in a Clone of That Tree


풀이

💻 결과코드

class Solution {
    public final TreeNode getTargetCopy(final TreeNode original, final TreeNode cloned, final TreeNode target) {
        return findTarget(original, cloned, target);
    }

    private TreeNode findTarget(TreeNode original, TreeNode cloned, TreeNode target) {
        if (original == null) return null;

        // 타겟 노드와 동일한 노드를 찾으면 클론된 트리의 현재 노드를 반환
        if (original == target) return cloned;

        // 왼쪽 서브트리 탐색
        TreeNode leftResult = findTarget(original.left, cloned.left, target);
        if (leftResult != null) return leftResult;

        // 오른쪽 서브트리 탐색
        return findTarget(original.right, cloned.right, target);
    }
}


public class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int x) { val = x; }
}

profile
Good Luck!

0개의 댓글