145. Binary Tree Postorder Trave

2020-08-29  本文已影响0人  jluemmmm

递归实现

/**
 * 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
};

更快的递归实现

/**
 * 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
};
上一篇下一篇

猜你喜欢

热点阅读