145. 二叉树的后序遍历 -力扣(leetCode)JS非递归解法

⚡️145. 二叉树的后序遍历⚡️
给定一个二叉树,返回它的 后序 遍历。

示例:
输入: [1,null,2,3]
1

2
/
3

输出: [3,2,1]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?

⚡️分析⚡️

用栈结构特性先进先出来解决,先压根节点,然后左,右,接着链表全部压入后;新建第二个栈,进行压入弹出。
例如:[1,2,3],先压入1到queue里,然后2,3分别压入栈,此时第一个栈为[2,3],接着3和2相继弹出压入queue,此时queue:[1,3,2],接着再将queue依次pop到需要返回的数组

代码如下:

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[]}
 */
var postorderTraversal = function(root) {
    if(!root) return [];
    const stack = [root];
    const q = [];
    while(stack.length) {
        const n = stack.pop();
        q.push(n);
        if(n.left) stack.push(n.left);
        if(n.right) stack.push(n.right);
    }
    const back = [];
    while(q.length) {
        const n = q.pop();
        back.push(n.val);
    }
    return back;
};

算法效率如图:
在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值