LeetCode热题(JS版)- 94. 二叉树的中序遍历

101 阅读1分钟

题目

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

示例 1:

image.png

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

示例 2:

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

示例 3:

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

提示:

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

思路:中序遍历

本题我们可以采用递归的方式来实现中序遍历。对于每个节点,我们先递归遍历其左子树,然后将当前节点的值加入结果数组中,最后递归遍历其右子树。 具体实现时,我们可以定义一个递归函数 inorderTraversal(node),表示遍历以 node 为根节点的子树。当节点 node 为 null 时,表示已经到达叶子节点,递归结束。否则,我们先递归遍历 node 的左子树,再将 node 的值加入结果数组中,最后递归遍历 node 的右子树。

  • 时间复杂度为 O(n),其中 n 是二叉树的节点个数。
  • 空间复杂度为 O(n),需要使用一个数组来存储中序遍历的结果。
/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function inorderTraversal(root: TreeNode | null): number[] {
    const res = [];
    // 左 - 中 - 右
    const traval = (root) => {
        if(!root) return;
        traval(root.left)
        res.push(root.val);
        traval(root.right)
    }
    traval(root);

    return res;
};

image.png