Skip to content

二叉树的后序遍历 #3

Open

Description

@YalongYan

leetcode 题目地址 二叉树的后序遍历

递归实现

var postorderTraversal = function(root) {
    let res = []
    function fn(node) {
        if (!node) {
            return
        }
        fn(node.left)
        fn(node.right)
        res.push(node.val)
    }
    fn(root)
    return res
};

非递归版

// 后续遍历的费递归版  就是把前序遍历 调整下,然后结果反过来
var postorderTraversal = function(root) {
    let res = []
    if (!root) {
        return []
    }
    let stack = [root]
    while(stack.length) {
        let n = stack.pop()
        res.push(n.val)
       // 跟前序遍历比,就下面两行 换了位置
        if(n.left) stack.push(n.left)
        if(n.right) stack.push(n.right)
    }
    return res.reverse()
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions