图文:深度优先遍历(DFS)和广度优先遍历(BFS)

/**
* 注意:left/right值若没有显示设置为null,值即为undefined
* 在调用二叉树前、中、后序遍历方法时,由于参数设置了默认值(tree)
* 所以进入了死循环
*/
const tree = {
    value: 5,
    left: {
        value: 3,
        left: {
            value: 2,
            left: null,
            right: null
        },
        right: {
            value: 4,
            left: null,
            right: null
        }
    },
    right: {
        value: 7,
        left: {
            value: 6,
            left: null,
            right: null
        },
        right: {
            value: 8,
            left: null,
            right: null
        }
    }
}
/**
* 二叉树
* 深度优先遍历
* 使用递归与前序遍历相同
* 使用栈的方式实现
*/
const depthFirstTravel = (node = tree) => {
    if(node === null) return 
    const stack = []
    stack.push(node)
    while(stack.length){
        const curNode = stack.pop()
        console.log(curNode.value)
        if(curNode.right){
            stack.push(curNode.right)
        }
        if(curNode.left){
            stack.push(curNode.left)
        }
    }
}

/**
* 二叉树
* 广度优先遍历
* 使用队列的方式实现
*/

const breadthFirstTravel = (node = tree) => {
    if(node === null) return
    const queue = []
    queue.push(node)
    while(queue.length){
        const curNode = queue.shift()
        console.log(curNode.value)
        if(curNode.left){
            queue.push(curNode.left)
        }
        if(curNode.right){
            queue.push(curNode.right)
        }
    }
}

 

posted @ 2023-01-27 23:27  671_MrSix  阅读(29)  评论(0编辑  收藏  举报