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

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

昨天刷了 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
};
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值