返回顶部

收藏

Go tree

更多
// Copyright 2011 The Go Authors.  All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package tree

import (
    "fmt"
    "math/rand"
)

// A Tree is a binary tree with integer values.
type Tree struct {
    Left  *Tree
    Value int
    Right *Tree
}

// New returns a new, random binary tree holding the values k, 2k, ..., 10k.
func New(k int) *Tree {
    var t *Tree
    for _, v := range rand.Perm(10) {
        t = insert(t, (1+v)*k)
    }
    return t
}

func insert(t *Tree, v int) *Tree {
    if t == nil {
        return &Tree{nil, v, nil}
    }
    if v < t.Value {
        t.Left = insert(t.Left, v)
    } else {
        t.Right = insert(t.Right, v)
    }
    return t
}

func (t *Tree) String() string {
    if t == nil {
        return "()"
    }
    s := ""
    if t.Left != nil {
        s += t.Left.String() + " "
    }
    s += fmt.Sprint(t.Value)
    if t.Right != nil {
        s += " " + t.Right.String()
    }
    return "(" + s + ")"
}
//该片段来自于http://outofmemory.cn

标签:golang,基础

收藏

0人收藏

支持

0

反对

0

»更多 您可能感兴趣的代码
  1. 2012-11-05 21:59:42java获得随机数代码 by 怪兽狂殴奥特曼
  2. 2016-10-18 15:14:10Introducing globals() by 蟋蟀MM
  3. 2016-10-31 09:15:18Automatically Initializing Mixed-In Modules by jeffsui
  4. 2016-11-14 09:31:24Taking Logarithms by digua
  5. 2016-11-25 09:29:54status fo an exception by 胡晋
  6. 2016-12-05 11:01:20use the ri tool: read the document by 胡晋
  7. 2016-12-13 16:54:52Symbol in an array by LeoSun
  8. 2016-12-21 09:54:07A pattern that matches a string containing the text Perl or the text Python by 好好学习啊
  9. 2017-01-04 11:04:59print command by 风云轩
  10. 2017-03-06 17:52:01Demonstrates global variables by 大猪
  11. 2017-03-23 10:29:44Guess My Number by jack.chen
相关聚客文章
  1. 无闻 发表 2014-01-16 07:00:00 《Go编程基础》视频教程
  2. 无闻 发表 2014-01-29 17:53:00 《Go Web基础》视频教程
  3. 博主 发表 2014-01-24 08:28:00 Go语言基础
  4. 无闻 发表 2014-01-16 07:00:00 《Go编程基础》视频教程
  5. 无闻 发表 2014-01-29 17:53:00 《Go Web基础》视频教程
  6. jack.zh 发表 2015-05-21 20:12:00 Go并发编程基础(译)
  7. noreply@blogger.com 发表 2013-02-06 17:30:00 Go maps in action
  8. 博主 发表 2013-05-21 23:06:47 Go 1.1 的性能提升
  9. 博主 发表 2013-06-17 01:35:48 可伸缩的食品包装:Eat & Go
  10. kingtent 发表 2013-06-26 14:06:40 UX基础:OmniGraffle新手指南
  11. Picturepan2 发表 2013-08-07 00:08:18 “零基础”WP 开发工具 Windows Phone App Studio
  12. Lerroy 发表 2013-08-30 11:51:44 经验分享:网页设计与重构那些事儿【基础篇】(原创技巧)

发表评论