Go语言普通二叉树

package main

import (
    "fmt"
)

type Tree struct {
    data string
    left *Tree
    right *Tree
}

func (tree *Tree) create_binary_tree(t *Tree) {
    var ch string
    fmt.Scanf("%s", &ch)
    if ch == "#" {
        t.data = ch
    } else {
        t.data = ch
        t.left = &Tree{}
        t.right = &Tree{}
        tree.create_binary_tree(t.left)
        tree.create_binary_tree(t.right)
    }
}

func (tree *Tree) pre_travel_binary_tree(t *Tree) {
    if t.left == nil && t.right == nil {
        fmt.Printf("%s ", t.data)
    } else {
        fmt.Printf("%s ", t.data)
        tree.pre_travel_binary_tree(t.left)
        tree.pre_travel_binary_tree(t.right)
    }
}

func (tree *Tree) in_travel_binary_tree(t *Tree) {
    if t.left == nil && t.right == nil {
        fmt.Printf("%s ", t.data)
    } else {
        tree.in_travel_binary_tree(t.left)
        fmt.Printf("%s ", t.data)
        tree.in_travel_binary_tree(t.right)
    }
}

func (tree *Tree) pos_travel_binary_tree(t *Tree) {
    if t.left == nil && t.right == nil {
        fmt.Printf("%s ", t.data)
    } else {
        tree.pos_travel_binary_tree(t.left)
        tree.pos_travel_binary_tree(t.right)
        fmt.Printf("%s ", t.data)
    }
}

func main() {
    var tree = &Tree{}
    tree.create_binary_tree(tree)

    tree.pre_travel_binary_tree(tree)
    fmt.Println()
    tree.in_travel_binary_tree(tree)
    fmt.Println()
    tree.pos_travel_binary_tree(tree)
    fmt.Println()
}

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

开始在上面输入您的搜索词,然后按回车进行搜索。按ESC取消。

返回顶部