实现思路:分治:先建立左子树,再建立右子树,然后合并两种情况。
/** * 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来实现:
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) } }
只知道不行动是纸上谈兵,只行动不思考更像是无头的苍蝇,要知行合一。