二叉树深度优先 之 先中后序遍历

二叉树深度优先 之 先中后序遍历

昨天刷了 leetcode 上面有关二叉树的三个遍历问题。 总结一下各自 非递归(迭代) 的算法。

  • 二叉树的遍历
    • 广度 优先遍历
    • 深度 优先遍历
      • 序遍历 => 根 – 左 – 右
      • 序遍历 => 左 – 根 – 右
      • 序遍历 => 左 – 右 – 根

先序遍历

应用:
打印一个结构化文档

思路如下

IMG_0237.jpeg

代码

var preorderTraversal = function(root) {
    const stack = []
    const res = []
    if (root) {stack.push(root)}
    while (stack.length) {
        const n = stack.pop()
        res.push(n.val)
        if(n.right) stack.push(n.right)
        if(n.left) stack.push(n.left)
    }
    return res
};
复制代码

中序遍历

应用:
对数进行排队操作

思路如下

IMG_0236.jpeg

代码

var inorderTraversal = function(root) {
    const stack = []
    const res = []
    let p = root
    while (stack.length || p) {
        while (p) {
            stack.push(p)
            p = p.left
        }
        const n = stack.pop()
        res.push(n.val)
        p = n.right
    }
    return res
};
复制代码

后序遍历

应用:
计算一个目录及其子目录中所以文件所占空间大小

思路如下

IMG_0238.jpeg

代码

var postorderTraversal = function(root) {
    const res = []
    const stack = []
    const outputStack = []
    if (root) stack.push(root)
    while (stack.length) {
        const n = stack.pop() 
        outputStack.push(n)
        n.left && stack.push(n.left)
        n.right && stack.push(n.right)
    }
    while (outputStack.length) {
        const n = outputStack.pop()
        res.push(n.val)
    }
    return res
};
复制代码
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享