Tuesday, August 04, 2015

if two binary trees are isomorphic

Two trees are isomorphic if two nodes' values are equal and their children are isomorphic as-is or swapped.
is-isomorphic-main(n1, n2):
    if n1 == null && n2 == null:
        throw
    return is-isomorphic(n1, n2)

is-isomorphic(n1, n2):
    if n1 == null && n2 == null:
        return true
    if n1 == null || n2 == null:
        return false
    return n1.value == n2.value
        && ((is-isomorphic(n1.left, n2.left) 
                && is-isomorphic(n1.right, n2.right))
            || (is-isomorphic(n1.left, n2.right) 
                && is-isomorphic(n1.right, n2.left)))

No comments:

Post a Comment