美文网首页
145. Binary Tree Postorder Trave

145. Binary Tree Postorder Trave

作者: jluemmmm | 来源:发表于2020-08-29 10:48 被阅读0次

    递归实现

    • Runtime: 72 ms, faster than 77.14%
    • Memory Usage: 37 MB, less than 17.86%
    /**
     * 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 []
        let res = []
        
        let recursive = function(node) {
            if(node.left) recursive(node.left)
            if(node.right) recursive(node.right)
            res.push(node.val)
        }
        recursive(root)
        return res
    };
    

    更快的递归实现

    • Runtime: 68 ms, faster than 91.12%
    • Memory Usage: 36.9 MB, less than 20.19%
    /**
     * 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) {
        let res = []
        recursive(root, res)
        return res
    };
    
    let recursive = function(node, res) {
        if(node) {
            if(node.left) recursive(node.left, res)
            if(node.right) recursive(node.right, res)
             node && res.push(node.val)
        }
        return
    }
    

    非递归实现

    /**
     * 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 []
        let stack = [root]
        let res = []
        
        while(stack.length > 0) {
            let { val, left, right } = stack.pop()
            res.unshift(val)
            left && stack.push(left)
            right && stack.push(right)
        }
        return res
    };
    

    相关文章

      网友评论

          本文标题:145. Binary Tree Postorder Trave

          本文链接:https://www.haomeiwen.com/subject/bwdojktx.html