题解 | #二叉树的后序遍历-递归和非递归#

二叉树的后序遍历

http://www.nowcoder.com/practice/1291064f4d5d4bdeaefbf0dd47d78541

递归思想:左右中,注意递归出口,res全局性

function postorderTraversal( root ) {
    // write code here
    const res = [];
    postOrder(root,res);
    return res;
}
function postOrder(root,res){
    if(!root) return;
    postOrder(root.left,res);
    postOrder(root.right,res);
    res.push(root.val);
}
module.exports = {
    postorderTraversal : postorderTraversal
};

非递归思想:两个栈!类似先序遍历,先把根出栈并押入辅助栈,但是先序是先右进栈后左进栈;后序则是左进栈右进栈。

	let res = []
    if(!root) return res;
    let stk1 = [root];
    let stk2 = [];
    
    while(stk1.length){
        const n = stk1.pop();
        stk2.push(n.val);
        //此处与先序顺序相反
        if(n.left) stk1.push(n.left);
        if(n.right) stk1.push(n.right);
    }
    //console.log(stk2)
    while(stk2.length){
        res.push(stk2.pop());
    }
    return res;
}
全部评论

相关推荐

不愿透露姓名的神秘牛友
07-04 18:02
好不容易拿到了字节Offer,鼠鼠做后端的,但家里人觉得可能被裁员不稳定,让鼠鼠去投国企,现在好纠结到底该咋选
文档传偷助手:该投就投吧,不过建议别放弃offer 拿到手里的才是最好的
投递字节跳动等公司8个岗位
点赞 评论 收藏
分享
不要停下啊:大二打开牛客,你有机会开卷了,卷起来,去找课程学习,在牛客上看看大家面试笔试都需要会什么,岗位有什么需求就去学什么,努力的人就一定会有收获,这句话从来都经得起考验,像我现在大三了啥也不会,被迫强行考研,炼狱难度开局,啥也不会,找工作没希望了,考研有丝丝机会
点赞 评论 收藏
分享
05-24 14:12
门头沟学院 Java
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务