leetcode 95. Unique Binary Search Trees II

实现思路:分治:先建立左子树,再建立右子树,然后合并两种情况。

/**
 * 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)
    }
}

 

转载于:https://www.cnblogs.com/Spider-spiders/p/10489011.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值