二叉树的遍历

参考:https://blog.csdn.net/qq_33243189/article/details/80222629
package main

import "fmt"

/**
*二叉树
×××二叉遍历
 */
func main() {
   d := NodeTree{"D", nil, nil}
   c := NodeTree{"C", &d, nil}
   b := NodeTree{"B", nil, &c}
   h := NodeTree{"H", nil, nil}
   k := NodeTree{"K", nil, nil}
   g := NodeTree{"G", &h, &k}
   f := NodeTree{"F", &g, nil}
   e := NodeTree{"E", nil, &f}
   a := NodeTree{"A", &b, &e}
   everyhouxu(&a)
}

/**
中序遍历:左-根-右
 */
func everyzhongxu(node *NodeTree) {
   if nil == node {
      return
   }
   courrent := node
   left := courrent.left
   right := courrent.right

   if nil == left {
      fmt.Println(courrent.data)
      courrent = right
      everyzhongxu(courrent)
      return
   }

   //输出左孩子
   everyzhongxu(left)
   //输出根节点
   fmt.Println(courrent.data)
   //输出右孩子
   everyzhongxu(right)

}

/**
前序
根左右
 */
func everyqianxu(nodetree *NodeTree) {
   if nil == nodetree {
      return
   }
   courrent := nodetree
   left := courrent.left
   right := courrent.right

   if nil != courrent {
      fmt.Println(courrent.data)
   }
   if nil != left {
      everyqianxu(left)
   }
   if nil != right {
      everyqianxu(right)
   }

   if nil == left && nil == right {
      return
   }

}

/**
后序
左右根
 */
func everyhouxu(nodetree *NodeTree) {
   if nil == nodetree {
      return
   }
   courrent := nodetree
   left := courrent.left
   right := courrent.right

   //左右为页节点时输出
   if nil != left {
      if nil == left.left && nil == left.right {
         fmt.Print(left.data)
      } else {
         everyhouxu(left)
      }

   }
   if nil != right {
      if nil == right.left && nil == right.right {
         fmt.Print(right.data)
      } else {
         everyhouxu(right)
      }
   }

   if nil != courrent {
      fmt.Print(courrent.data)
   }

}

/**
层序遍历
 */
func cengxu(tree *NodeTree) {
   if nil == tree {
      return
   }
   var quece [] *NodeTree
   quece = append(quece, tree)

   for ; 0 != len(quece); {

      node := quece[0]
      fmt.Print(node.Data)
      quece = quece[1:] //第一个元素出队
      if nil != node.Left { //出栈元素的左右元素顺序进队
         quece = append(quece, node.Left)
      }
      if nil != node.Right {
         quece = append(quece, node.Right)
      }

   }

}
type NodeTree struct {
   data  string
   left  *NodeTree
   right *NodeTree
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值