1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| /** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func isCousins(root *TreeNode, x int, y int) bool { xParentNode, xDepth := dfs(root, nil, 0, x) yParentNode, yDepth := dfs(root, nil, 0, y) return xParentNode != yParentNode && xDepth == yDepth }
func dfs(curNode, parentNode *TreeNode, depth, target int) (int, int) { if curNode == nil { return -1, -1 } if curNode.Val == target { if parentNode == nil { return 0, depth } return parentNode.Val, depth } if leftParentNode, leftDepth := dfs(curNode.Left, curNode, depth+1, target); leftParentNode != -1 { return leftParentNode, leftDepth } return dfs(curNode.Right, curNode, depth+1, target) }
|