二分樹的3種遍歷
尚硅谷Golang課

二分樹的3種遍歷

package main

import "fmt"

type Hero struct {
	No    int
	Name  string
	Left  *Hero
	Right *Hero
}

//前序遍歷 先輸出root 再輸出左子樹 再輸出右子樹,會中左右一層層往下
func PreOrder(node *Hero) {
	if node != nil {
		fmt.Printf("no=%d name=%s\n", node.No, node.Name)
		PreOrder(node.Left)
		PreOrder(node.Right)
	}
}

//中序遍歷 左子樹 root 右子樹
func InfixOrder(node *Hero) {
	if node != nil {
		InfixOrder(node.Left)
		fmt.Printf("no=%d name=%s\n", node.No, node.Name)
		InfixOrder(node.Right)
	}
}

//後序遍歷 左子樹  右子樹 root,會一路到最左最下開始打
func PostOrder(node *Hero) {
	if node != nil {
		PostOrder(node.Left)
		PostOrder(node.Right)
		fmt.Printf("no=%d name=%s\n", node.No, node.Name)

	}
}

func main() {
	//建一個二分樹
	root := &Hero{
		No:   1,
		Name: "宋江",
	}

	left1 := &Hero{
		No:   2,
		Name: "無用",
	}

	right1 := &Hero{
		No:   3,
		Name: "你軌",
	}
	root.Left = left1
	root.Right = right1
	right2 := &Hero{
		No:   4,
		Name: "林沖",
	}
	right1.Right = right2
	node21 := &Hero{
		No:   21,
		Name: "無用-下左",
	}
	node22 := &Hero{
		No:   22,
		Name: "無用-下右",
	}
	left1.Left = node21
	left1.Right = node22

	PreOrder(root)
	fmt.Println("==========")
	InfixOrder(root)
	fmt.Println("==========")
	PostOrder(root)

}

上次修改於 2021-09-01

此篇文章的評論功能已經停用。