feat(tree): add binary tree dfs in golang

This commit is contained in:
reanon 2022-11-26 14:36:43 +08:00
parent 0f89475e0e
commit e62d663630
2 changed files with 93 additions and 0 deletions

View file

@ -0,0 +1,63 @@
// 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"
)
// preOrder 前序遍历
func preOrder(root *TreeNode) (nums []int) {
var preOrderHelper func(node *TreeNode)
// 匿名函数
preOrderHelper = func(node *TreeNode) {
if node == nil {
return
}
// 访问优先级:根结点 -> 左子树 -> 右子树
nums = append(nums, node.Val)
preOrderHelper(node.Left)
preOrderHelper(node.Right)
}
// 函数调用
preOrderHelper(root)
return
}
// inOrder 中序遍历
func inOrder(root *TreeNode) (nums []int) {
var inOrderHelper func(node *TreeNode)
// 匿名函数
inOrderHelper = func(node *TreeNode) {
if node == nil {
return
}
// 访问优先级:左子树 -> 根结点 -> 右子树
inOrderHelper(node.Left)
nums = append(nums, node.Val)
inOrderHelper(node.Right)
}
// 函数调用
inOrderHelper(root)
return
}
// postOrder 后序遍历
func postOrder(root *TreeNode) (nums []int) {
var postOrderHelper func(node *TreeNode)
// 匿名函数
postOrderHelper = func(node *TreeNode) {
if node == nil {
return
}
// 访问优先级:左子树 -> 右子树 -> 根结点
postOrderHelper(node.Left)
postOrderHelper(node.Right)
nums = append(nums, node.Val)
}
// 函数调用
postOrderHelper(root)
return
}

View file

@ -0,0 +1,30 @@
// File: binary_tree_dfs_test.go
// Created Time: 2022-11-26
// Author: Reanon (793584285@qq.com)
package chapter_tree
import (
. "github.com/krahets/hello-algo/pkg"
"testing"
)
func TestPreInPostOrderTraversal(t *testing.T) {
/* 初始化二叉树 */
// 这里借助了一个从数组直接生成二叉树的函数
root := ArrayToTree([]int{1, 2, 3, 4, 5, 6, 7})
t.Log("初始化二叉树: ")
PrintTree(root)
// 前序遍历
nums := preOrder(root)
t.Log("前序遍历的结点打印序列 = ", nums)
// 中序遍历
nums = inOrder(root)
t.Log("中序遍历的结点打印序列 = ", nums)
// 后序遍历
nums = postOrder(root)
t.Log("后序遍历的结点打印序列 = ", nums)
}