코딩테스트 풀이/JAVA
[LeetCode/Easy] 1379. Find a Corresponding Node of a Binary Tree in a Clone of That Tree
무지맘
2023. 6. 12. 01:36
1. Input
1) final TreeNode original
2) final TreeNode cloned
- original을 복사한 트리
3) final TreeNode target
- original의 노드 중 하나
2. Output
1) cloned에서 target과 같은 것을 찾아 반환
3. Constraint
1) 트리의 노드 수의 범위는 [1, 10^4]이다.
2) 노드의 값에는 중복이 없다.
3) 타겟 노드는 null이 아니다.
4. Example
Input: tree = [7,4,3,null,null,6,19], target = 3 -> Output: 3
설명: 왼쪽 트리가 original, 오른쪽 트리가 cloned, 연두색이 target, 노란색이 반환해야 할 노드이다.
5. Code
1) 첫 코드(2023/06/12)
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public final TreeNode getTargetCopy(final TreeNode original, final TreeNode cloned, final TreeNode target) {
Queue<TreeNode> q = new LinkedList<>();
q.add(cloned);
TreeNode c = null;
while(!q.isEmpty()){
c = q.remove();
if(c.val==target.val) break;
if(c.left!=null) q.add(c.left);
if(c.right!=null) q.add(c.right);
}
return c;
}
}
- 14%, 71%