145.二叉树的后序遍历

题目

给定一个二叉树,返回它的 后序 遍历。

示例:

输入: [1,null,2,3]  
   1
    \
     2
    /
   3 
输出: [3,2,1]

进阶: 递归算法很简单,你可以通过迭代算法完成吗?

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/binary-tree-postorder-traversal 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路

后序遍历:左 -> 右 -> 根

JS实现

1、递归实现

/**
 * 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 helper = function (root, result) {
  if (root != null) {
    if (root.left != null) {
      helper(root.left, result);
    }
    if (root.right != null) {
      helper(root.right, result);
    }
    result.push(root.val);
  }
};

var postorderTraversal = function (root) {
  const result = [];
  if (root === null) {
    return result;
  }
  helper(root, result);
  return result;
};

2、迭代实现

var postorderTraversal = function (root) {
  const result = [];
  if (root === null) {
    return result;
  }

  // 栈的特点:先进后出
  const stack = [];

  // 根元素入栈
  stack.push(root);

  while (stack.length > 0) {
    // 取出栈顶元素
    const node = stack.pop();
    // unshift在数组开头插入元素
    result.unshift(node.val);

    // 我们需要先取出右节点,所以把左节点先入栈
    if (node.left != null) {
      stack.push(node.left);
    }
    if (node.right != null) {
      stack.push(node.right);
    }
  }
  return result;
};