码迷,mamicode.com
首页 > 其他好文 > 详细

二叉树操作

时间:2019-05-06 19:15:17      阅读:117      评论:0      收藏:0      [点我收藏+]

标签:func   code   port   pack   sea   nod   package   min   return   

package main import "fmt" type Node struct { Key int Left * Node Right * Node } func (n *Node) Insert(key int) { if key < n.Key{ if n.Left == nil{ n.Left = &Node{Key:key} } n.Left.Insert(key) }else if key > n.Key{ if n.Right == nil{ n.Right = &Node{Key:key} } n.Right.Insert(key) } } //中序打印 func (n * Node)print() { if n == nil{ return } n.Left.print() fmt.Println(n.Key) n.Right.print() } //前序打印 func (n * Node)printpre() { if n == nil{ return } fmt.Println(n.Key) n.Left.printpre() n.Right.printpre() } //后序打印 func (n * Node)printend() { if n == nil{ return } n.Left.printend() n.Right.printend() fmt.Println(n.Key) } //查询 func (n * Node)Search(key int) bool { if n == nil{ return false } if n.Key < key{ n.Right.Search(key) }else if n.Key > key{ return n.Left.Search(key) } return true } //删除 func (n * Node)Delete(key int) *Node { if n == nil{ return nil } if n.Key < key{ n.Right = n.Right.Delete(key) }else if n.Key > key{ n.Left = n.Left.Delete(key) }else { if n.Left == nil{ return n.Right }else if n.Right == nil{ return n.Left }else { min := n.Right.Min() n.Key = min n.Right = n.Right.Delete(min) } } return n } //求最小值 func (n *Node)Min() int { if n.Left==nil{ return n.Key } return n.Left.Min() } func main() { root := &Node{Key:8} root.Insert(3) root.Insert(10) root.Insert(1) root.Insert(6) root.Insert(14) root.Insert(4) root.Insert(7) root.Insert(13) fmt.Println("=====================中序打印==================================") root.print() fmt.Println("======================前序打印================================") root.printpre() fmt.Println("=======================后序打印================================") root.printend() if root.Search(10){ fmt.Println("found") }else { fmt.Println("not found") } if root.Search(100){ fmt.Println("found") }else { fmt.Println("not found") } if root.Search(0){ fmt.Println("found") }else { fmt.Println("not found") } root.Delete(6) root.Delete(3) root.print() }

二叉树操作

标签:func   code   port   pack   sea   nod   package   min   return   

原文地址:https://blog.51cto.com/slapping/2390022

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!