145. Binary Tree Postorder Traversal

题干简述:

给我们一个二叉树的根节点,求该二叉树后序遍历结果。

解题思路

数据结构与算法课中必教的内容,前中后序遍历。使用 DFS 递归实现可以说是没有难度,重点就在于左右子树递归函数的执行位置与当前节点处理逻辑的相对位置关系。

BFS 要稍微复杂一点,可以参考 144. Binary Tree Preorder Traversal 中的解法,后序遍历相比于前序遍历,注意下节点处理的顺序即可。

题解

/**
 * 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[]}
 */
// DFS 解法
var postorderTraversal = function(root) {
    const res = [];
    const dfs = (node) => {
        if (!node) return;
        dfs(node.left);
        dfs(node.right);
        res.push(node.val);
    };
    dfs(root);
    return res;
};

// BFS 解法
var postorderTraversal = function(root) {
    if (!root) return [];
    const res = [];
    const queue = [root];
    while (queue.length) {
        const node = queue.pop();
        if (!node) continue;
        res.unshift(node.val);
        queue.push(node.left);
        queue.push(node.right);
    };
    return res;
};

Q.E.D.


Take it easy