Created
January 19, 2021 08:23
-
-
Save charlieInDen/12b68ebcb587b116213023bfffdd444b to your computer and use it in GitHub Desktop.
Cousins in Binary Tree
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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