Skip to content

Instantly share code, notes, and snippets.

@sourcedelica
Created September 10, 2015 02:41
Show Gist options
  • Save sourcedelica/082cf525acf4973fa618 to your computer and use it in GitHub Desktop.
Save sourcedelica/082cf525acf4973fa618 to your computer and use it in GitHub Desktop.
/**
* Determine if both arrays of keys would form the same BSTs
* without building the trees
*/
def isSameBST(arr1: Array[Int], arr2: Array[Int]): Boolean = {
// Compute the paths from root to node for each element
def paths(arr: Array[Int]): Map[Int, String] = {
var map = Map.empty[Int, String]
// For each element
arr.indices foreach { i =>
var path = ""
// Compare with elements before it
(0 until i) foreach { j =>
// If the path for the previous element is the same as the path for
// the current element up to now, append the branch this element will take
if (path == map(arr(j))) path += (if (arr(i) < arr(j)) 'L' else 'R')
}
// Save path for element
map += arr(i) -> path
}
map
}
// Compute set of paths for each array and compare them
paths(arr1) == paths(arr2)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment