首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何在Golang中实现二叉树的中序遍历

在Golang中实现二叉树的中序遍历可以通过递归或者非递归的方式来实现。下面给出两种实现方式的代码示例:

  1. 递归方式实现中序遍历:
代码语言:txt
复制
package main

import "fmt"

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

func inorderTraversal(root *TreeNode) []int {
    var result []int
    inorder(root, &result)
    return result
}

func inorder(node *TreeNode, result *[]int) {
    if node == nil {
        return
    }
    inorder(node.Left, result)
    *result = append(*result, node.Val)
    inorder(node.Right, result)
}

func main() {
    // 构建二叉树
    root := &TreeNode{Val: 1}
    root.Left = &TreeNode{Val: 2}
    root.Right = &TreeNode{Val: 3}
    root.Left.Left = &TreeNode{Val: 4}
    root.Left.Right = &TreeNode{Val: 5}

    // 中序遍历二叉树
    result := inorderTraversal(root)
    fmt.Println(result) // 输出 [4 2 5 1 3]
}
  1. 非递归方式实现中序遍历(借助栈):
代码语言:txt
复制
package main

import (
    "fmt"
)

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

func inorderTraversal(root *TreeNode) []int {
    var result []int
    stack := []*TreeNode{}
    node := root
    for node != nil || len(stack) != 0 {
        for node != nil {
            stack = append(stack, node)
            node = node.Left
        }
        node = stack[len(stack)-1]
        stack = stack[:len(stack)-1]
        result = append(result, node.Val)
        node = node.Right
    }
    return result
}

func main() {
    // 构建二叉树
    root := &TreeNode{Val: 1}
    root.Left = &TreeNode{Val: 2}
    root.Right = &TreeNode{Val: 3}
    root.Left.Left = &TreeNode{Val: 4}
    root.Left.Right = &TreeNode{Val: 5}

    // 中序遍历二叉树
    result := inorderTraversal(root)
    fmt.Println(result) // 输出 [4 2 5 1 3]
}

以上是在Golang中实现二叉树的中序遍历的两种方法。这两种方法都可以实现二叉树的中序遍历,递归方式更简洁易懂,而非递归方式则可以减少函数调用的开销。具体选择哪种方法取决于实际需求和个人喜好。

腾讯云相关产品和产品介绍链接地址:

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券