본문으로 바로가기
반응형

Description

원본트리와 복사된 이진트리가 주어졌을때 원본 target 노드와 동일한 위치의 clone트리의 노드를 반환하는 문제입니다.

Given two binary trees original and cloned and given a reference to a node target in the original tree.

The cloned tree is a copy of the original tree.

Return a reference to the same node in the cloned tree.

Note that you are not allowed to change any of the two trees or the target node and the answer must be a reference to a node in the cloned tree.

Example 1:

Input: tree = [7,4,3,null,null,6,19], target = 3
Output: 3
Explanation: In all examples the original and cloned trees are shown. The target node is a green node from the original tree. The answer is the yellow node from the cloned tree.

Example 2:

Input: tree = [7], target =  7
Output: 7

Example 3:

Input: tree = [8,null,6,null,5,null,4,null,3,null,2,null,1], target = 4
Output: 4

Constraints:

  • The number of nodes in the tree is in the range [1, 10^4].
  • The values of the nodes of the tree are unique.
  • target node is a node from the original tree and is not null.

Follow up: Could you solve the problem if repeated values on the tree are allowed?

Solution 1. DFS(Depth First Search)

TreeNode cloneTarget;

public TreeNode getTargetCopy(final TreeNode original, final TreeNode cloned, final TreeNode target) {
    inorderTraversal(original, cloned, target);
    return cloneTarget;
}

private void  inorderTraversal(TreeNode original, TreeNode cloned, TreeNode target) {
    if(original == null) return;
    inorderTraversal(original.left,cloned.left,target);
    if(original == target) cloneTarget = cloned;
    inorderTraversal(original.right,cloned.right,target);
}

재귀호출을 통한 DFS(깊이우선탐색)방법으로 중위 순회(inorderTraversal)을 통해 트리를 탐색해 나가며 타겟과 일치 할 경우 clone 트리의 해당 노드를 반환해줍니다.

Solution 2. BFS(Breadth First Search)

public TreeNode getTargetCopy(final TreeNode original, final TreeNode cloned, final TreeNode target) {

    //2. Iteration (BFS with Queue)
    if(original == null) return null;
    
    Queue<TreeNode> q = new LinkedList<>();
    Queue<TreeNode> cq = new LinkedList<>();

    q.offer(original);
    cq.offer(cloned);

    while(!q.isEmpty()){

        TreeNode originCur = q.poll();
        TreeNode cloneCur = cq.poll();

        if(originCur == target) return cloneCur;

        if(originCur.left != null) q.offer(originCur.left);
        if(cloneCur.left != null) cq.offer(cloneCur.left);
        if(originCur.right != null) q.offer(originCur.right);
        if(cloneCur.right != null) cq.offer(cloneCur.right);
    }

    return null;
}

BFS(너비우선탐색)을 통해 큐를 이용한 반복으로 트리를 탐색해 나가며 타겟의 위치를 반환해 줍니다.

Reference

 

Find a Corresponding Node of a Binary Tree in a Clone of That Tree - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

반응형

댓글을 달아 주세요