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

  • 相关阅读:
    json 总结
    Django---admin简单功能
    Django---Models
    Django---Template(模板)
    Django---URL、Views
    Django---定义、MVC和MTV模式、命令行工具、配置文件settings
    必学算法
    一个虚拟社交公司的融资历程
    分布式系统,本文引用“courage”的博客
    mysql语句
  • 原文地址:https://www.cnblogs.com/gaopeng527/p/6699626.html
Copyright © 2011-2022 走看看