立诚勿怠,格物致知
It's all about connecting the dots

二叉树前序遍历的非递归实现

二叉树前序遍历的非递归实现:

function Node (data, left, right) {
    this.data = data
    this.left = left || null
    this.right = right || null
}

function BST () {
    this.root = null
}

function insertNode (parentNode, newNode) {
    if (newNode.data < parentNode.data) {
        if (parentNode.left === null) {
            parentNode.left = newNode
        } else {
            insertNode(parentNode.left, newNode)
        }
    } else {
        if (parentNode.right === null) {
            parentNode.right = newNode
        } else {
            insertNode(parentNode.right, newNode)
        }
    }
}

BST.prototype.insert = function (data) {
    const node = new Node(data, null, null)
    if (this.root === null) {
        this.root = node
    } else {
        insertNode(this.root, node)
    }
}

const bst = new BST();
[23, 45, 16, 37, 3, 99, 22].forEach((item) => {
    bst.insert(item)
})

function preTraverseBST (bst) {
    let node = bst.root
    let arr = [node] // 作为一个栈来使用,只用它的shift和unshift方法
    while (node !== null && arr.length > 0) {
        console.log(node.data)
        if (node.left !== null) {
            arr.unshift(node.left)
            node = node.left
        } else {
            node = arr.shift()
            while (node.right === null && arr.length > 0) {
                node = arr.shift()
            }
            node = node.right
            arr.unshift(node)
        }
    }
}

preTraverseBST(bst)

 

赞(0) 打赏
文章名称:《二叉树前序遍历的非递归实现》
文章链接:https://www.orzzone.com/binary-search-tree-preorder-traverse-none-recursion.html
商业联系:yakima.public@gmail.com

本站大部分文章为原创或编译而来,对于本站版权文章,未经许可不得用于商业目的,非商业性转载请以链接形式标注原文出处。
本站内容仅供个人学习交流,不做为任何投资、建议的参考依据,因此产生的问题需自行承担。

评论 抢沙发

觉得文章有用就打赏一下文章作者

非常感谢你的打赏,我们将继续给力提供更多优质内容!

支付宝扫一扫打赏

微信扫一扫打赏

登录

找回密码

注册