Repository: vaskoz/dailycodingproblem-go (go)

Issue:
Day 278
Good morning! Here's your coding interview problem for today.

This problem was asked by Amazon.

Given an integer `N`, construct all possible binary search trees with `N` nodes.

Pull request description:
Day278
Resolves #565.

Patch:
diff --git a/README.md b/README.md
index db05312..e24f75b 100644
--- a/README.md
+++ b/README.md
@@ -282,5 +282,6 @@ problems from
 * [Day 272](https://github.com/vaskoz/dailycodingproblem-go/issues/555)
 * [Day 273](https://github.com/vaskoz/dailycodingproblem-go/issues/556)
 * [Day 277](https://github.com/vaskoz/dailycodingproblem-go/issues/563)
+* [Day 278](https://github.com/vaskoz/dailycodingproblem-go/issues/565)
 * [Day 279](https://github.com/vaskoz/dailycodingproblem-go/issues/566)
 * [Day 280](https://github.com/vaskoz/dailycodingproblem-go/issues/568)
diff --git a/day278/problem.go b/day278/problem.go
new file mode 100644
index 0000000..3a13033
--- /dev/null
+++ b/day278/problem.go
@@ -0,0 +1,33 @@
+package day278
+
+// BST is an integer binary search tree.
+type BST struct {
+	Value       int
+	Left, Right *BST
+}
+
+func ConstructAllPossibleBSTs(n int) []*BST {
+	return constructAllPossibleBSTs(1, n)
+}
+
+func constructAllPossibleBSTs(start, end int) []*BST {
+	var result []*BST
+	if start > end {
+		return []*BST{nil}
+	}
+	for i := start; i < end+1; i++ {
+		left := constructAllPossibleBSTs(start, i-1)
+		right := constructAllPossibleBSTs(i+1, end)
+		for j := range left {
+			l := left[j]
+			for k := range right {
+				r := right[k]
+				node := &BST{Value: i}
+				node.Left = l
+				node.Right = r
+				result = append(result, node)
+			}
+		}
+	}
+	return result
+}


Test patch:
diff --git a/day278/problem_test.go b/day278/problem_test.go
new file mode 100644
index 0000000..e999264
--- /dev/null
+++ b/day278/problem_test.go
@@ -0,0 +1,54 @@
+package day278
+
+import (
+	"reflect"
+	"testing"
+)
+
+// nolint
+var testcases = []struct {
+	n         int
+	preorders [][]int
+}{
+	{
+		3,
+		[][]int{
+			{1, 2, 3},
+			{1, 3, 2},
+			{2, 1, 3},
+			{3, 1, 2},
+			{3, 2, 1},
+		},
+	},
+}
+
+func TestConstructAllPossibleBSTs(t *testing.T) {
+	t.Parallel()
+	for _, tc := range testcases {
+		result := ConstructAllPossibleBSTs(tc.n)
+		preorders := make([][]int, 0, len(result))
+		for _, root := range result {
+			preorders = append(preorders, preorder(root, []int{}))
+		}
+		if !reflect.DeepEqual(preorders, tc.preorders) {
+			t.Errorf("Expected %v, got %v", tc.preorders, preorders)
+		}
+	}
+}
+
+func BenchmarkConstructAllPossibleBSTs(b *testing.B) {
+	for i := 0; i < b.N; i++ {
+		for _, tc := range testcases {
+			ConstructAllPossibleBSTs(tc.n)
+		}
+	}
+}
+
+func preorder(root *BST, lst []int) []int {
+	if root != nil {
+		lst = append(lst, root.Value)
+		lst = preorder(root.Left, lst)
+		lst = preorder(root.Right, lst)
+	}
+	return lst
+}