2022-11-26 06:36:43 +00:00
|
|
|
// File: binary_tree_dfs.go
|
|
|
|
// Created Time: 2022-11-26
|
|
|
|
// Author: Reanon (793584285@qq.com)
|
|
|
|
|
|
|
|
package chapter_tree
|
|
|
|
|
|
|
|
import (
|
|
|
|
. "github.com/krahets/hello-algo/pkg"
|
|
|
|
)
|
|
|
|
|
2022-12-03 12:25:24 +00:00
|
|
|
var nums []int
|
|
|
|
|
|
|
|
/* 前序遍历 */
|
|
|
|
func preOrder(node *TreeNode) {
|
|
|
|
if node == nil {
|
|
|
|
return
|
2022-11-26 06:36:43 +00:00
|
|
|
}
|
2022-12-03 12:25:24 +00:00
|
|
|
// 访问优先级:根结点 -> 左子树 -> 右子树
|
|
|
|
nums = append(nums, node.Val)
|
|
|
|
preOrder(node.Left)
|
|
|
|
preOrder(node.Right)
|
2022-11-26 06:36:43 +00:00
|
|
|
}
|
|
|
|
|
2022-12-03 12:25:24 +00:00
|
|
|
/* 中序遍历 */
|
|
|
|
func inOrder(node *TreeNode) {
|
|
|
|
if node == nil {
|
|
|
|
return
|
2022-11-26 06:36:43 +00:00
|
|
|
}
|
2022-12-03 12:25:24 +00:00
|
|
|
// 访问优先级:左子树 -> 根结点 -> 右子树
|
|
|
|
inOrder(node.Left)
|
|
|
|
nums = append(nums, node.Val)
|
|
|
|
inOrder(node.Right)
|
2022-11-26 06:36:43 +00:00
|
|
|
}
|
|
|
|
|
2022-12-03 12:25:24 +00:00
|
|
|
/* 后序遍历 */
|
|
|
|
func postOrder(node *TreeNode) {
|
|
|
|
if node == nil {
|
|
|
|
return
|
2022-11-26 06:36:43 +00:00
|
|
|
}
|
2022-12-03 12:25:24 +00:00
|
|
|
// 访问优先级:左子树 -> 右子树 -> 根结点
|
|
|
|
postOrder(node.Left)
|
|
|
|
postOrder(node.Right)
|
|
|
|
nums = append(nums, node.Val)
|
2022-11-26 06:36:43 +00:00
|
|
|
}
|