zoukankan      html  css  js  c++  java
  • Go语言二叉树定义及遍历算法实现

    // binary_tree 二叉树
    package Algorithm
    
    import (
        "reflect"
    )
    
    // 二叉树定义
    type BinaryTree struct {
        Data   interface{}
        Lchild *BinaryTree
        Rchild *BinaryTree
    }
    
    // 构造方法
    func NewBinaryTree(data interface{}) *BinaryTree {
        return &BinaryTree{Data: data}
    }
    
    // 先序遍历
    func (bt *BinaryTree) PreOrder() []interface{} {
        t := bt
        stack := NewStack(reflect.TypeOf(bt))
        res := make([]interface{}, 0)
        for t != nil || !stack.Empty() {
            for t != nil {
                res = append(res, t.Data)
                stack.Push(t)
                t = t.Lchild
            }
            if !stack.Empty() {
                v, _ := stack.Pop()
                t = v.(*BinaryTree)
                t = t.Rchild
            }
        }
        return res
    }
    
    // 中序遍历
    func (bt *BinaryTree) InOrder() []interface{} {
        t := bt
        stack := NewStack(reflect.TypeOf(bt))
        res := make([]interface{}, 0)
        for t != nil || !stack.Empty() {
            for t != nil {
                stack.Push(t)
                t = t.Lchild
            }
            if !stack.Empty() {
                v, _ := stack.Pop()
                t = v.(*BinaryTree)
                res = append(res, t.Data)
                t = t.Rchild
            }
        }
        return res
    }
    
    // 后续遍历
    func (bt *BinaryTree) PostOrder() []interface{} {
        t := bt
        stack := NewStack(reflect.TypeOf(bt))
        s := NewStack(reflect.TypeOf(true))
        res := make([]interface{}, 0)
        for t != nil || !stack.Empty() {
            for t != nil {
                stack.Push(t)
                s.Push(false)
                t = t.Lchild
            }
            for flag, _ := s.Top(); !stack.Empty() && flag.(bool); {
                s.Pop()
                v, _ := stack.Pop()
                res = append(res, v.(*BinaryTree).Data)
                flag, _ = s.Top()
            }
            if !stack.Empty() {
                s.Pop()
                s.Push(true)
                v, _ := stack.Top()
                t = v.(*BinaryTree)
                t = t.Rchild
            }
        }
        return res
    }

    github链接:https://github.com/gaopeng527/go_Algorithm/blob/master/binary_tree.go

  • 相关阅读:
    27-Perl 进程管理
    26-Perl 包和模块
    25-Perl CGI编程
    YUM极速安装mariadb
    yum极速安装mysql5.7
    切换阿里yum镜像源
    mysql生成随机字符串函数
    Unable to locate value meta plugin of type (id)
    centos 挂载NTFS移动硬盘
    总有你要的编程书单(GitHub )
  • 原文地址:https://www.cnblogs.com/gaopeng527/p/6699626.html
Copyright © 2011-2022 走看看