每天学习一点算法 2026/03/09
题目:二叉树的中序遍历
给定一个二叉树的根节点
root,返回 它的 中序 遍历 。
-
递归法:中序遍历就是
left → root → right,所以我们需要在root.left递归调用和root.right递归调用的中间记录节点值。/** * 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 arr = [] function helper (root: TreeNode | null) { if (root === null) { return } helper(root.left) arr.push(root.val) helper(root.right) } helper(root) return arr }; -
迭代法
function inorderTraversal(root: TreeNode | null): number[] { const arr = [] const stack = [] while (root || stack.length) { // 进入到最左侧叶子结点 while (root) { stack.push(root) root = root.left } // 往回遍历 root = stack.pop() arr.push(root.val) // 访问当前root的右节点 root = root.right } return arr };
题目来源:力扣(LeetCode)

863

被折叠的 条评论
为什么被折叠?



