美文网首页
[二叉树] 二叉树的层次遍历

[二叉树] 二叉树的层次遍历

作者: 爱上落入尘世间的你 | 来源:发表于2017-11-13 18:48 被阅读0次

    思路:借助于一个队列,实现从上到下,每一层从左到右的遍历

    首先将根节点入队,算是完成了初始化

    然后不断循环,直到队列为空

    在每一轮的循环中,从队列中取出一个节点(第一次循环当然取出的就是根节点了),访问它
    如果这个节点有左节点,把左节点放进队列
    如果这个节点有右节点,把右节点放进队列
    然后进入下一轮循环

    function levelIterate(root)
    {
        const nodes = [] // 节点队列
        nodes.unshift(root) // 根节点入队
    
        while(nodes.length > 0)
        {
            const current = nodes.pop() // 队列中取出一个节点
            touch(current) // 访问该节点
            if(current.left)
            {
                nodes.unshift(current.left)
            }
            if(current.right)
            {
                nodes.unshift(current.right)
            }
        }
    }
    
    function touch(node)
    {
        console.log(node.value)
    }
    

    相关文章

      网友评论

          本文标题:[二叉树] 二叉树的层次遍历

          本文链接:https://www.haomeiwen.com/subject/oattvxtx.html