// P55 (**) Construct completely balanced binary trees. // In a completely balanced binary tree, the following property holds for // every node: The number of nodes in its left subtree and the number of // nodes in its right subtree are almost equal, which means their difference // is not greater than one. // // Define an object named Tree. Write a function Tree.cBalanced to // construct completely balanced binary trees for a given number of nodes. // The function should generate all solutions. The function should take as // parameters the number of nodes and a single value to put in all of them. // // scala> Tree.cBalanced(4, "x") // res0: List(Node[String]) = List(T(x T(x . .) T(x . T(x . .))), T(x T(x . .) T(x T(x . .) .)), ... object Tree { def cBalanced[T](nodes: Int, value: T): List[Tree[T]] = nodes match { case n if n < 1 => List(End) case n if n % 2 == 1 => { val subtrees = cBalanced(n / 2, value) subtrees.flatMap(l => subtrees.map(r => Node(value, l, r))) } case n if n % 2 == 0 => { val lesserSubtrees = cBalanced((n - 1) / 2, value) val greaterSubtrees = cBalanced((n - 1) / 2 + 1, value) lesserSubtrees.flatMap(l => greaterSubtrees.flatMap(g => List(Node(value, l, g), Node(value, g, l)))) } } }