[路飞]_二叉树的后续遍历

391 阅读1分钟

题目介绍

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

示例

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

输出: [3,2,1]

leetcode-145 二叉树的后续遍历
b站视频

解题思路

解法一:递归

递归方法比较简单,不做过多介绍

解题代码

var postorderTraversal = function(root) {
    const arr = []
    postorder(root, arr)
    return arr
};

var postorder = function(root, arr) {
    if (!root) return
    postorder(root.left, arr)
    postorder(root.right, arr)
    arr.push(root.val)
}

解法二:迭代

迭代通过栈的方式来实现

  1. 先将根节点入栈
  2. 当栈不为空时,弹出栈顶节点,将该节点的值插入到数组的头部,然后将该节点的左节点和右节点依次入栈
  3. 重复步骤 2,直到栈为空
  4. 返回数组

2.gif

解题代码

var postorderTraversal = function(root) {
    const res = []
    if (!root) return res
    const stack = [root]
    while (stack.length) {
        root = stack.pop()
        res.unshift(root.val)
        if (root.left) stack.push(root.left)
        if (root.right) stack.push(root.right)
    }
    return res
};