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

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
}

你可能感兴趣的:(leetcode刷题,leetcode,二叉树,中序遍历,算法)