Algorithm
993 : Cousins in Binary Tree ( leetcode / java )
코동이
2020. 10. 30. 10:57
*해결과정
우리가 필요한 것은 depth(깊이), parent(부모)이다. 새로운 배열을 만들어서 DFS순회를 돌면서 depth와 parent를 갱신하면 된다. 굳이 새로운 class를 만들 것 없이 매개변수로 전달하면 된다.
class Solution {
int xDepth=0;
int yDepth=0;
int xParent = 0;
int yParent = 0;
public boolean isCousins(TreeNode root, int x, int y) {
DFS(root,x,y,0,-1);
return (xDepth==yDepth) && (xParent!=yParent);
}
public void DFS(TreeNode root, int x, int y, int depth,int parent){
if(root.val==x) {
xDepth = depth;
xParent = parent;
}
if(root.val==y) {
yDepth = depth;
yParent = parent;
}
if(root.left!=null) DFS(root.left,x,y,depth+1, root.val);
if(root.right!=null) DFS(root.right,x,y,depth+1, root.val);
}
}
반응형