Skip to content

Instantly share code, notes, and snippets.

@charlieInDen
Created January 19, 2021 08:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save charlieInDen/12b68ebcb587b116213023bfffdd444b to your computer and use it in GitHub Desktop.
Save charlieInDen/12b68ebcb587b116213023bfffdd444b to your computer and use it in GitHub Desktop.
Cousins in Binary Tree
func isCousins(_ root: TreeNode?, _ x: Int, _ y: Int) -> Bool {
var queue: [(node: TreeNode, depth: Int, parentVal: Int)] = [(root!, 0, -1)]
var xd: (depth: Int?, parentVal: Int) = (nil, -1), yd: (depth: Int?, parentVal: Int) = (nil, -1)
while queue.count > 0 {
let (node, depth, parentVal) = queue.removeLast()
if node.val == x { xd = (depth, parentVal) }
if node.val == y { yd = (depth, parentVal) }
if xd.depth != nil && yd.depth != nil { return xd.depth == yd.depth && xd.parentVal != yd.parentVal }
if node.left != nil { queue.append((node.left!, depth + 1, node.val)) }
if node.right != nil { queue.append((node.right!, depth + 1, node.val)) }
}
return false
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment