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

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

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

function TreeNode(x) {
    this.val = x;
    this.left = null;
    this.right = null;
}

function threeOrders(root) {
    const pre = [];
    const inOrder = [];
    const post = [];

    // 先序遍历函数
    function preorder(node) {
        if (!node) return;
        pre.push(node.val);
        preorder(node.left);
        preorder(node.right);
    }

    // 中序遍历函数
    function inorder(node) {
        if (!node) return;
        inorder(node.left);
        inOrder.push(node.val);
        inorder(node.right);
    }

    // 后序遍历函数
    function postorder(node) {
        if (!node) return;
        postorder(node.left);
        postorder(node.right);
        post.push(node.val);
    }

    // 执行三种遍历
    preorder(root);
    inorder(root);
    postorder(root);

    return [pre, inOrder, post];
}

module.exports = {
    threeOrders: threeOrders,
};

全部评论

相关推荐

MrGaomq:你沟通的太少了,我两个号沟通了都1w多了
点赞 评论 收藏
分享
04-21 16:05
已编辑
山西大学 Java
不吃压力👿:我和你简历差不多,好多看到28就不回复了,回复的基本是全栈或低代码
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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