Featured image of post 94. 二叉树的中序遍历

94. 二叉树的中序遍历

题目描述

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

示例 1:

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

示例 2:

  • 输入:root = []
  • 输出:[]

示例 3:

  • 输入:root = [1]
  • 输出:[1]

提示:

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

进阶: 递归算法很简单,你可以通过迭代算法完成吗?

解法一:递归

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func inorderTraversal(root *TreeNode) []int {
    var res []int
    var inorder func(root* TreeNode)
    inorder = func(root* TreeNode) {
        if root == nil {
            return
        }
        inorder(root.Left)
        res = append(res, root.Val)
        inorder(root.Right)
    }
    inorder(root)
    return res
}

解法二:迭代

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func inorderTraversal(root *TreeNode) []int {
    var stack []*TreeNode
    var result []int
    for len(stack) > 0 || root != nil {
        for root != nil {
            stack = append(stack, root)
            root = root.Left
        }
        root = stack[len(stack)-1]
        stack = stack[:len(stack)-1]
        result = append(result, root.Val)
        root = root.Right
    }
    return result
}
comments powered by Disqus
Built with Hugo
主题 StackJimmy 设计