在Go(Golang)中构建二进制树的后序遍历的程序

64 阅读1分钟

概述

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

  • 访问左边的子树

  • 访问右小树

  • 访问根部

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

那么后序遍历将是

[4 2 5 6 3 1]

程序

package main

import (
	"fmt"
)

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

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

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

	output := make([]int, 0)

	output = append(output, left...)

	output = append(output, right...)

	output = append(output, root.Val)
	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 := postorderTraversal(&root)
	fmt.Println(output)

}

输出

[4 2 5 6 3 1]