二叉树的遍历

这篇博客详细介绍了二叉树的四种遍历方法:前序、中序、后序遍历以及层序遍历,并提供了相应的JavaScript实现。同时,讲解了如何计算二叉树的最大深度,包括两种递归和非递归的解决方案。这些内容对于理解和操作二叉树数据结构至关重要。
摘要由CSDN通过智能技术生成

目录

前序、中序、后序

层序遍历

二叉树的最大深度


深度优先 DFS                          广度优先 BFS

前序、中序、后序遍历             层序遍历

前序、中序、后序

function preorderTraversal (root) {
    if (!root) return [];
    const res = [];

    function traversal (root) {
        res.push(root.val);   // 中序inorderTraversal 放中间,后序postorderTraversal 放最后
        root.left && traversal(root.left);
        root.right && traversal(root.right);
    }
    traversal(root);
    return res;
}

层序遍历

结果为一维数组,利用栈:

function levelOrder (root) {
    if (!root) return [];
    const queue = [root];
    const res = [];

    while (queue.length) {
        const node = queue.shift();
        res.push(node.val);
        node.left && queue.push(node.left);
        node.right && queue.push(node.right);
    }
    return res;
}

结果是按层次存储的二维数组,使用迭代:

function levelOrder (root) {
    if (!root) return [];
    const res = [];
    // 记录深度depth
    function traversal (root, depth) {
        if (!res[depth]) res[depth] = [];
        res[depth].push(root.val); 
        root.left && traversal(root.left, depth + 1);
        root.right && traversal(root.right, depth + 1);
    }
    traversal(root, 0);
    return res;
}

二叉树的最大深度

function maxDepth (root) {
    if (!root) return 0;
    return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值