- 이진 트리가 주어지면 트리의 각 노드 값을 모든 사촌 값의 합으로 바꾼다.
- 이진 트리의 두 노드는 서로 다른 부모와 동일한 깊이를 갖는 경우 사촌이다.
- 노드의 깊이는 루트 노드에서 루트 노드까지의 경로에 있는 가장자리의 수다.
- 수정된 트리를 반환 하라.
- 즉, x와 y가 사촌이면 true, 아니면 false를 반환하는 문제이다.
Input: root = [1,2,3,4], x = 4, y = 3
Output: false
Input: root = [1,2,3,null,4,null,5], x = 5, y = 4
Output: true
Input: root = [1,2,3,null,4], x = 2, y = 3
Output: false
트리의 노드 수는 범위 내에 있습니다.
1 <= Node.val <= 100
각 노드에는 고유한 값이 있습니다.
x != y
x 와 y는 트리에 존재합니다.
/**
* Definition for a binary tree node.
* 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;
* }
* }
*/
class Solution {
int xP = 0;
int yP = 0;
int xD = 0;
int yD = 0;
public boolean isCousins(TreeNode root, int x, int y) {
if (root == null) return false;
FindCousins(root, x, y, 0, 0);
if(xP != yP && xD == yD) return true;
else return false;
}
public void FindCousins(TreeNode root, int x, int y, int depth, int parent) {
if(root.val == x){
xP = parent;
xD = depth;
}
if(root.val == y) {
yP = parent;
yD = depth;
}
if(root.left != null) FindCousins(root.left, x, y, depth+1, root.val);
if(root.right != null) FindCousins(root.right, x, y, depth+1, root.val);
}
}