概述package main import ( "container/list" "fmt" ) // Binary Tree type BinaryTree struct { Data interface{} Left *BinaryTree Right *BinaryTree } // Constructor func NewBinaryTree(data int package main import ( "container/List" "fmt" ) // 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二叉树前序,中序,后序非递归遍历算法全部内容,希望文章能够帮你解决golang二叉树前序,中序,后序非递归遍历算法所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
评论列表(0条)