题解 | 实现二叉树先序,中序和后序遍历

实现二叉树先序,中序和后序遍历

https://www.nowcoder.com/practice/a9fec6c46a684ad5a3abd4e365a9d362

/*
 * function TreeNode(x) {
 *   this.val = x;
 *   this.left = null;
 *   this.right = null;
 * }
 */
/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 *
 * @param root TreeNode类 the root of binary tree
 * @return int整型二维数组
 */
function threeOrders(root) {
    // 先序遍历生成器
    const func1 = function* (root) {
        if (root === null) return; // 如果当前节点为空,直接返回
        yield root.val; // 访问当前节点
        if (root.left) yield* func1(root.left); // 遍历左子树
        if (root.right) yield* func1(root.right); // 遍历右子树
    };

    // 中序遍历生成器
    const func2 = function* (root) {
        if (root === null) return; // 如果当前节点为空,直接返回
        if (root.left) yield* func2(root.left); // 遍历左子树
        yield root.val; // 访问当前节点
        if (root.right) yield* func2(root.right); // 遍历右子树
    };

    // 后序遍历生成器
    const func3 = function* (root) {
        if (root === null) return; // 如果当前节点为空,直接返回
        if (root.left) yield* func3(root.left); // 遍历左子树
        if (root.right) yield* func3(root.right); // 遍历右子树
        yield root.val; // 访问当前节点
    };

    const result = [];
    result.push([...func1(root)]); // 先序遍历结果
    result.push([...func2(root)]); // 中序遍历结果
    result.push([...func3(root)]); // 后序遍历结果

    return result; // 返回结果
}
module.exports = {
    threeOrders: threeOrders,
};

生成器解法

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-11 11:22
怎么这么多逆天求职者,救救我救救我救救我😭
flmz_Kk:哈哈哈哈哈哈,这么多求职者,肯定有那一两个逆天的
点赞 评论 收藏
分享
MinJerous:虽然我一直说 计算机不怎么卡学历 但是至少得一本
点赞 评论 收藏
分享
07-05 16:23
门头沟学院 Java
mengnankk:我投了300,约了5 6个面试。感觉项目写的太多了。一个项目就写五六个亮点,不是把整个项目的功能描述下。其他的没啥,简历看起来有点长
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务