Jquery中文网 www.jquerycn.cn
Jquery中文网 >  后端编程  >  Go语言  >  正文 Golang算法:二叉树前序,中序,后序非递归遍历算法

Golang算法:二叉树前序,中序,后序非递归遍历算法

发布时间:2021-05-17   编辑:www.jquerycn.cn
jquery中文网为您提供Golang算法:二叉树前序,中序,后序非递归遍历算法等资源,欢迎您收藏本站,我们将为您提供最新的Golang算法:二叉树前序,中序,后序非递归遍历算法资源

本文主要介绍了二叉树前序,中序,后序非递归遍历算法

import (
   "container/list"
)
// Binary Tree
type BinaryTree struct {
   Data  interface{}
   Left  *BinaryTree
   Right *BinaryTree
}
// Constructor
func NewBinaryTree(data interface{}) *BinaryTree {
   return &BinaryTree{Data: data}
}
// 先序遍历-非递归
func (bt *BinaryTree) PreOrderNoRecursion() []interface{} {
   t := bt
   stack := list.New()
   res := make([]interface{}, 0)
   for t != nil || stack.Len() != 0 {
      for t != nil {
         res = append(res, t.Data)//visit
         stack.PushBack(t)
         t = t.Left
      }
      if stack.Len() != 0 {
         v := stack.Back()
         t = v.Value.(*BinaryTree)
         t = t.Right
         stack.Remove(v)
      }
   }
   return res
}
// 中序遍历-非递归
func (bt *BinaryTree) InOrderNoRecursion() []interface{} {
   t := bt
   stack := list.New()
   res := make([]interface{}, 0)
   for t != nil || stack.Len() != 0 {
      for t != nil {
         stack.PushBack(t)
         t = t.Left
      }
      if stack.Len() != 0 {
         v := stack.Back()
         t = v.Value.(*BinaryTree)
         res = append(res, t.Data)//visit
         t = t.Right
         stack.Remove(v)
      }
   }
   return res
}
// 后序遍历-非递归
func (bt *BinaryTree) PostOrderNoRecursion() []interface{} {
   t := bt
   stack := list.New()
   res := make([]interface{}, 0)
   var preVisited *BinaryTree
   for t != nil || stack.Len() != 0 {
      for t != nil {
         stack.PushBack(t)
         t = t.Left
      }
      v   := stack.Back()
      top := v.Value.(*BinaryTree)
      if (top.Left == nil && top.Right == nil) || (top.Right == nil && preVisited == top.Left) || preVisited == top.Right{
         res = append(res, top.Data)//visit
         preVisited = top
         stack.Remove(v)
      }else {
         t = top.Right
      }
   }
   return res
}
func main() {
   t := NewBinaryTree(1)
   t.Left  = NewBinaryTree(3)
   t.Right = NewBinaryTree(6)
   t.Left.Left = NewBinaryTree(4)
   t.Left.Right = NewBinaryTree(5)
   t.Left.Left.Left = NewBinaryTree(7)
   fmt.Println(t.PreOrderNoRecursion())
   fmt.Println(t.InOrderNoRecursion())
   fmt.Println(t.PostOrderNoRecursion())
}
到此这篇关于“Golang算法:二叉树前序,中序,后序非递归遍历算法”的文章就介绍到这了,更多文章或继续浏览下面的相关文章,希望大家以后多多支持JQ教程网!

您可能感兴趣的文章:
Golang算法:二叉树前序,中序,后序非递归遍历算法
php 二叉树遍历算法与例子
二叉链表表示的二叉树及基本操作
数据结构中树与二叉树基础算法的比较
java中二叉树遍历(递归) 程序代码
关于二叉树的深度算法题目及解答
PHP快速排序算法实现的原理及代码介绍
Python中的二叉排序树和平衡二叉树是什么
PHP递归算法的实例程序
C 实现二叉查找树过程详解教程【图】

上一篇:Go语言_接口查询 下一篇:golang sync/atomic
[关闭]