JS树的遍历

本文介绍了如何使用JavaScript实现树的遍历,包括递归方式的先序、中序、后序遍历以及非递归的层次遍历方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. 递归形式的先序、中序、后序 + 非递归层次遍历:
//树的数据结构
function TreeNode(x){
    this.val = x;
    this.left = null;
    this.right = null;
}

//先序遍历(Degree Left Right)
function DLR(root){
    console.log(root.val);
    if(root.left){
        DLR(root.left);
    }
    if(root.right){
        DLR(root.right);
    }
}

//中序遍历(Left Degree Right)
function LDR(root){
    if(root.left){
        LDR(root.left);
    }
    console.log(root.val);
    if(root.right){
        LDR(root.right);
    }
}

//后序遍历(Left Right Degree)
function LRD(root){
    if(root.left){
        LRD(root.left);
    }
    if(root.right){
        LRD(root.right);
    }
    console.log(root.val);
}

//层次遍历
function levelTraversal(root){
    if(!root) return false; //如果头结点为空,返回假
    let result = [];    //创建一个数组,存放结果
    let tree = [];  //创建一个数组存放二叉树
    tree.push(root);    //先传入头结点

    //当tree数组长度不为空
    while(tree.length){
        let node = tree.shift();    //将数组第一个结点放到node中
        result.push(node.val);  //将node结点的值压到result数组中
        //如果node结点左子树不为空
        if(node.left){
            tree.push(node.left);
        }
        //如果node结点右子树不为空
        if(node.right){
            tree.push(node.right);
        }
    }
    return result;
}

let tnode = new TreeNode(3);
tnode.left = {"val":2};
tnode.right = {"val":1};
console.log(tnode);
console.log("先序遍历:");
DLR(tnode);
console.log("中序遍历:");
LDR(tnode);
console.log("后序遍历:");
LRD(tnode);
console.log("层次遍历:",levelTraversal(tnode));

在这里插入图片描述

  1. 非递归形式的先序、中序、后序

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值