/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func find(root *TreeNode, depth int, x int) (*TreeNode, int) {
if root == nil {
return nil, -1 // not found
}
if root.Left != nil && root.Left.Val == x || root.Right != nil && root.Right.Val == x {
return root, depth
}
leftP, leftD := find(root.Left, depth+1, x)
if leftD != -1 {
return leftP, leftD
}
rightP, rightD := find(root.Right, depth+1, x)
if rightD != -1 {
return rightP, rightD
}
return nil, -1
}
func isCousins(root *TreeNode, x int, y int) bool {
px, dx := find(root, 0, x)
py, dy := find(root, 0, y)
if dx == -1 || dy == -1 {
return false
}
return px != py && dx == dy
}