Go(Golang)中二进制树的预排序遍历

84 阅读1分钟

概述

在二叉树的前序遍历中,我们遵循以下顺序

  • 访问根部

  • 访问左子树

  • 访问右小树

例如,假设我们有以下二叉树

那么前序遍历将是

[1 2 4 3 5 6]

程序

以下是相同的程序

package main

import (
	"fmt"
)

type TreeNode struct {
	Val   int
	Left  *TreeNode
	Right *TreeNode
}

func preorderTraversal(root *TreeNode) []int {
	if root == nil {
		return nil
	}

	left := preorderTraversal(root.Left)
	right := preorderTraversal(root.Right)

	output := make([]int, 0)

	output = append(output, root.Val)
	output = append(output, left...)
	output = append(output, right...)
	return output
}

func main() {
	root := TreeNode{Val: 1}
	root.Left = &TreeNode{Val: 2}
	root.Left.Left = &TreeNode{Val: 4}
	root.Right = &TreeNode{Val: 3}
	root.Right.Left = &TreeNode{Val: 5}
	root.Right.Right = &TreeNode{Val: 6}

	output := preorderTraversal(&root)
	fmt.Println(output)

}

输出

[1 2 4 3 5 6]