Problem:
In a binary tree, the root node is at depth 0, and children of each depth k node are at depth k+1.
Two nodes of a binary tree are cousins if they have the same depth, but have different parents.
We are given the root of a binary tree with unique values, and the values x and y of two different nodes in the tree.
Return true if and only if the nodes corresponding to the values x and y are cousins.
Explanation:
表兄弟是指在同一深度但是父母不同的结点,判断给定的两个结点是否是表兄弟。
My Thinking:
遍历,维护两个结点的父母和深度即可。
My Solution:
class Solution {
private int xdepth=0;
private int ydepth=0;
private TreeNode xparent=null;
private TreeNode yparent=null;
public boolean isCousins(TreeNode root, int x, int y) {
findDepthAndParent(root,x,y,0,null);
if(xparent!=yparent && xdepth==ydepth){
return true;
}else{
return false;
}
}
public void findDepthAndParent(TreeNode root, int x, int y,int depth,TreeNode parent) {
if(root==null)
return;
if(root.val==x){
xdepth=depth;
xparent=parent;
}
if(root.val==y){
ydepth=depth;
yparent=parent;
}
findDepthAndParent(root.left,x,y,depth+1,root);
findDepthAndParent(root.right,x,y,depth+1,root);
}
}
Optimum Thinking:
Optimum Solution: