js 前端算法------大厂面试笔试题(二叉树的深度优先遍历)

今日分享的是二叉树的深度优先遍历(按先序遍历讲解)
二叉树
1.二叉树深度遍历通俗易懂的来讲就是优先往深处走,就是看有没子节点,从左到右比如从1 开始遍历,从左往右走,有没有子节点,有是2,就再看2遍历完了再看5以此类推
2.那么二叉树和栈的结合就是利用栈的后进先出的特点,从右往左把子节点放在栈中依次取出遍历
3.用js实现

//模拟一个二叉树
let tree={
     
    value:1,
    childleft:{
     
        value:2,
        childleft:{
     
            value:3,
        },
        childright:{
     
            value:4,
        },
    },
    childright:{
     
        value:5,
        childright:{
     
            value:6
        }
    }
}
//非递归的实现
function bianli(tree){
     
    let list=[];
    let stack=[tree];//用数组模拟栈,先把树放了进去
    while(stack.length!==0){
     
        let target=stack.pop()//根据栈的后进先出用pop()取到数组的末尾
        list.push(target.value)//把值放进数组里
        if(target.childright){
     //右子叉树是否存在,若存在放在栈里
            stack.push(target.childright)//把右叉树放在栈里
        }
        if(target.childleft){
     
            stack.push(target.childleft)//把左叉树放在栈里
        }
    }
    return list//返回遍历后的数组
}
console.log(bianli(tree))

//递归实现
let result = [];
let dfs = function (node) {
     
    if(node) {
     
        result.push(node.value);
        dfs(node.left);
        dfs(node.right);
    }
}

dfs(tree);
console.log(result);

广度优先遍历

//递归实现
let result = [];
let stack = [tree]; // 先将要遍历的树压入栈
let count = 0; // 用来记录执行到第一层
let bfs = function () {
     
    let node = stack[count];
    if(node) {
     
        result.push(node.value);
        if(node.left) stack.push(node.left);
        if(node.right) stack.push(node.right);
        count++;
        bfs();
    }
}
dfc();
console.log(result);
//  ["-", "+", "/", "a", "*", "d", "e", "b", "c"]

你可能感兴趣的:(study,progress,数据结构,二叉树,stack,栈)