golang二叉树

``` package main import ( "fmt" queue "test2/Queue" ) type Node struct { value string Left, Right *Node } var q queue.ItemQueue //创建 func CreateNode(val string) *Node { return &Node{value: val, Left: nil, Right: nil} } //设置节点的值 func (node *Node) SetValue(val string) { node.value = val } //打印 func (node *Node) Print() { fmt.Printf("%+v\n", *node) } //前序遍历 func (node *Node) PreOrder() { if node == nil { return } node.Print() node.Left.PreOrder() node.Right.PreOrder() } //中序遍历 func (node *Node) MidOrder() { if node == nil { return } node.Left.MidOrder() node.Print() node.Right.MidOrder() } //后序遍历 func (node *Node) PostOrder() { if node == nil { return } node.Left.PostOrder() node.Right.PostOrder() node.Print() } //广度优先遍历 func (root *Node) Bforder() { q.Enqueue(root) for { item := q.Dequeue() node, ok := item.(*Node) if ok { node.Print() if node.Left != nil { q.Enqueue(node.Left) } if node.Right != nil { q.Enqueue(node.Right) } if q.IsEmpty() { break } } } } //获取高度 //取两个子节点中大的高度+1 func (node *Node) GetTreeHeight() int { if node == nil { return 0 } lHight := node.Left.GetTreeHeight() rHight := node.Right.GetTreeHeight() if lHight >= rHight { return lHight + 1 } else { return rHight + 1 } } func main() { root := CreateNode("A") root.Left = CreateNode("B") root.Right = CreateNode("C") root.Left.Left = CreateNode("D") root.Left.Right = CreateNode("E") root.Right.Left = CreateNode("F") root.Right.Right = CreateNode("G") root.Bforder() } ```

你可能感兴趣的:(golang二叉树)