(Javascript)二叉树的非递归遍历——前序、中序、后序

一、二叉树的前序、后序遍历

1、视频解析

(1)前序遍历+后续遍历
https://www.bilibili.com/video/BV15f4y1W7i2?from=search&seid=4673079064082377683
(2)中序遍历
https://www.bilibili.com/video/BV1Zf4y1a77g/?spm_id_from=333.788.recommend_more_video.-1

2、leetcode题目链接

(1)前序遍历题目链接
https://leetcode-cn.com/problems/binary-tree-preorder-traversal/
(2)后序遍历题目链接
https://leetcode-cn.com/problems/binary-tree-postorder-traversal/

3、具体代码

(1)二叉树 前序遍历 迭代法 代码

var preorderTraversal = function(root) {
    let res = [];
    let stack = [];
    stack.push(root);
     while(stack.length) {
        let node = stack.pop();//利用栈实现非递归遍历
        if(node !== null) {
            res.push(node.val);
        }else {
            continue;
        }
        if(node.right) {
            stack.push(node.right);
        }
        if(node.left) {
            stack.push(node.left);
        }
    }
    return res;
};

(2)二叉树 后序遍历 迭代法 代码

// 利用前序遍历(中左右) -> 左右对调(中右左) -> 数组翻转(左右中),即得到后续遍历(左右中)
var postorderTraversal = function(root) {
    let res = [];
    let stack = [];
    stack.push(root);
    while(stack.length) {
        let node = stack.pop();
        if(node !== null) {
            res.push(node.val);
        }else {
            continue;
        }
        if(node.left) {
            stack.push(node.left);
        }
        if(node.right) {
            stack.push(node.right);
        }
    }
    return res.reverse();
};

(3)二叉树 中序遍历 迭代法 代码

var inorderTraversal = function(root) {
    let res = [];
    let stack = [];
    let cur = root;
    while(stack.length !== 0 || cur !== null) {
        if(cur !== null) {
            stack.push(cur);
            cur = cur.left;
        }else {
            cur = stack.pop();
            res.push(cur.val);
            cur = cur.right;
        }
    }
    return res;
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值