實現思路:分治:先創建左子樹,再創建右子樹,而後合併兩種狀況。node
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func generateTrees(n int) []*TreeNode { if n < 1 { return nil } return createTrees(1, n) } func createTrees(begin int, end int) []*TreeNode { var trees []*TreeNode if begin > end { trees = append(trees, nil) } for i := begin; i <= end; i++ { leftTrees := createTrees(begin, i-1) rightTrees := createTrees(i+1, end) for _, left := range leftTrees { for _, right := range rightTrees { root := TreeNode{i, left, right} trees = append(trees, &root) } } } return trees }
因爲左子樹和右子樹是相互獨立的子問題,那麼其實能夠同時進行,使用goroutine來實現:app
package main import "fmt" // Definition for a binary tree node. type TreeNode struct { Val int Left *TreeNode Right *TreeNode } func generateTrees(n int) []*TreeNode { begin := make(chan int, 1) end := make(chan int, 1) result := make(chan []*TreeNode) // var resultArr []*TreeNode if n < 1 { return nil } begin <- 1 end <- n go createTrees(begin, end, result) myresult := <-result return myresult } func createTrees(begin chan int, end chan int, treesChan chan []*TreeNode) { // var trees []*TreeNode leftTrees := make(chan []*TreeNode) rightTrees := make(chan []*TreeNode) mid := make(chan int, 1) var rootset, leftTreesR, rightTreesR []*TreeNode b := <-begin e := <-end if b > e { rootset = append(rootset, nil) } for i := b; i <= e; i++ { mid <- (i - 1) begin <- b go createTrees(begin, mid, leftTrees) mid <- (i + 1) end <- e go createTrees(mid, end, rightTrees) leftTreesR = <-leftTrees rightTreesR = <-rightTrees for _, left := range leftTreesR { for _, right := range rightTreesR { root := TreeNode{i, left, right} rootset = append(rootset, &root) } } } treesChan <- rootset } func main() { trees := generateTrees(20) for _, value := range trees { fmt.Println(value) } }