首頁 > 軟體

詳解Go語言如何實現二元樹遍歷

2022-04-19 19:02:15

1. 二元樹的定義

二元樹需滿足的條件

① 本身是有序樹

② 樹中包含的各個節點的長度不能超過2,即只能是0、1或者2

2. 前序遍歷

前序遍歷二元樹的順序:根——》左——》右

package main

import "fmt"

//定義結構體
type Student struct {
	Name  string
	Age   int
	Score float32
	left  *Student //左子樹指標
	right *Student //右子樹指標
}

//二元樹定義
func main() {
	//根節點
	var root Student
	root.Name = "root"
	root.Age = 18
	root.Score = 88

	//一級左子樹
	var left1 Student
	left1.Name = "left1"
	left1.Age = 20
	left1.Score = 80

	root.left = &left1

	//一級右子樹
	var right1 Student
	right1.Name = "right1"
	right1.Age = 22
	right1.Score = 100

	root.right = &right1

	//二級左子樹
	var left2 Student
	left2.Name = "left2"
	left2.Age = 25
	left2.Score = 90

	left1.left = &left2

	//呼叫遍歷函數
	Req(&root)

}

//遞迴演演算法遍歷整個二元樹
func Req(tmp *Student) {
	for tmp == nil {
		return
	}
	fmt.Println(tmp)
	//遍歷左子樹
	Req(tmp.left)
	//遍歷右子樹
	Req(tmp.right)
}

輸出結果如下

&{root 18 88 0xc0000c0480 0xc0000c04b0}
&{left1 20 80 0xc0000c04e0 <nil>}
&{left2 25 90 <nil> <nil>}
&{right1 22 100 <nil> <nil>}

3. 中序遍歷

中序遍歷:左——》根——》右

package main

import "fmt"

//定義結構體
type Student struct {
	Name  string
	Age   int
	Score float32
	left  *Student //左子樹指標
	right *Student //右子樹指標
}

//二元樹定義
func main() {
	//根節點
	var root Student
	root.Name = "root"
	root.Age = 18
	root.Score = 88

	//一級左子樹
	var left1 Student
	left1.Name = "left1"
	left1.Age = 20
	left1.Score = 80

	root.left = &left1

	//一級右子樹
	var right1 Student
	right1.Name = "right1"
	right1.Age = 22
	right1.Score = 100

	root.right = &right1

	//二級左子樹
	var left2 Student
	left2.Name = "left2"
	left2.Age = 25
	left2.Score = 90

	left1.left = &left2

	//呼叫遍歷函數
	Req(&root)

}

//遞迴演演算法遍歷整個二元樹
func Req(tmp *Student) {
	for tmp == nil {
		return
	}

	//遍歷左子樹
	Req(tmp.left)

	//輸出root節點
	fmt.Println(tmp)

	//遍歷右子樹
	Req(tmp.right)
}

輸出結果如下

&{left2 25 90 <nil> <nil>}
&{left1 20 80 0xc000114510 <nil>}
&{root 18 88 0xc0001144b0 0xc0001144e0}
&{right1 22 100 <nil> <nil>}

4. 後序遍歷

後序遍歷:左——》右——》根

package main

import "fmt"

//定義結構體
type Student struct {
	Name  string
	Age   int
	Score float32
	left  *Student //左子樹指標
	right *Student //右子樹指標
}

//二元樹定義
func main() {
	//根節點
	var root Student
	root.Name = "root"
	root.Age = 18
	root.Score = 88

	//一級左子樹
	var left1 Student
	left1.Name = "left1"
	left1.Age = 20
	left1.Score = 80

	root.left = &left1

	//一級右子樹
	var right1 Student
	right1.Name = "right1"
	right1.Age = 22
	right1.Score = 100

	root.right = &right1

	//二級左子樹
	var left2 Student
	left2.Name = "left2"
	left2.Age = 25
	left2.Score = 90

	left1.left = &left2

	//呼叫遍歷函數
	Req(&root)

}

//遞迴演演算法遍歷整個二元樹
func Req(tmp *Student) {
	for tmp == nil {
		return
	}

	//遍歷左子樹
	Req(tmp.left)

	//遍歷右子樹
	Req(tmp.right)

	//輸出root節點
	fmt.Println(tmp)

}

輸出結果如下

&{left2 25 90 <nil> <nil>}
&{left1 20 80 0xc0000c04e0 <nil>}
&{right1 22 100 <nil> <nil>}
&{root 18 88 0xc0000c0480 0xc0000c04b0}

到此這篇關於詳解Go語言如何實現二元樹遍歷的文章就介紹到這了,更多相關Go語言二元樹遍歷內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!


IT145.com E-mail:sddin#qq.com