LeetCode 「简单」94.二叉树的中序遍历
题目描述
给定一个二叉树的根节点 root ,返回 它的 中序 遍历 。
示例
输入:root = [1,null,2,3]
输出:[1,3,2]
输入:root = []
输出:[]
输入:root = [1]
输出:[1]
解答
递归
Code
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
var inorderTraversal = function(root) {
if (!root) return [];
const result = [];
const dfs = (node) => {
if (!node) return;
dfs(node.left);
result.push(node.val);
dfs(node.right);
};
dfs(root);
return result;
};
迭代
Code
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
var inorderTraversal = function(root) {
if (!root) return [];
const result = []; // 用于存储中序遍历的结果
const stack = []; // 使用栈来模拟递归的过程
let current = root; // 当前访问的节点
// 遍历整棵树
while (current || stack.length > 0) {
// 先将当前节点的所有左子节点压入栈
while (current) {
stack.push(current);
current = current.left;
}
// 当前节点为空,说明需要从栈中弹出一个节点
current = stack.pop();
result.push(current.val);
// 转向右子树
current = current.right;
}
return result;
}
