LeetCode94. 二叉树的中序遍历Golang版

本文介绍了解决LeetCode94题——二叉树中序遍历的方法,包括递归和迭代两种实现方式。通过具体示例展示了如何获取一棵二叉树的中序遍历结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

LeetCode94. 二叉树的中序遍历Golang版

1. 问题描述

给定一个二叉树的根节点 root ,返回它的 中序 遍历。

示例 1:

输入:root = [1,null,2,3]
输出:[1,3,2]
示例 2:

输入:root = []
输出:[]
示例 3:

输入:root = [1]
输出:[1]
示例 4:

输入:root = [1,2]
输出:[2,1]
示例 5:

输入:root = [1,null,2]
输出:[1,2]

提示:

树中节点数目在范围 [0, 100] 内
-100 <= Node.val <= 100

2. 思路

2.1. 递归

2.3. 中序遍历

3. 代码

3.1. 递归代码

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func inorderTraversal(root *TreeNode) []int {
    var res []int
    inorder(root, &res)
    return res
}

func inorder(root *TreeNode, res *[]int) {
    if root == nil {
        return
    }

    inorder(root.Left, res)
    *res = append(*res, root.Val)
    inorder(root.Right, res)

}

3.2. 迭代代码

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func inorderTraversal(root *TreeNode) []int {
    var res []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]
        res = append(res, node.Val)
        node = node.Right
        stack = stack[:len(stack) - 1]
    }
    return res
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值