BT2 二叉树的中序遍历
约 171 字小于 1 分钟
2025-04-15
描述
给定一个二叉树的根节点root,返回它的中序遍历结果。
链接
示例
{1,2,#,#,3} => [2,3,1]
{} => []
{1,2} => [2,1]
{1,#,2} => [1,2]题解
/*
* function TreeNode(x) {
* this.val = x;
* this.left = null;
* this.right = null;
* }
*/
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @return int整型一维数组
*/
function inorderTraversal(root) {
// write code here
function go(tree, arr) {
if (tree) {
go(tree.left, arr);
arr.push(tree.val);
go(tree.right, arr);
}
}
let res = [];
go(root, res);
return res;
}
module.exports = {
inorderTraversal: inorderTraversal,
};