给你一棵二叉树的根节点 root ,返回其节点值的 后序遍历 。
示例 1:
输入: root = [1,null,2,3]
输出: [3,2,1]
示例 2:
输入: root = []
输出: []
题解:
/**
* 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) {
// 后序遍历:左、右、头
// 方法一:递归
// inorder(root) 递归头节点
// inorder(root.left) 递归左节点
// inorder(root.right) 递归右节点
const stack = []
const inorder = (root) => {
if (!root) return
inorder(root.left)
inorder(root.right)
stack.push(root.val)
}
inorder(root)
return stack
// 方法二:迭代
// 头节点入栈
// 1、从s1栈内弹出栈内节点cur
// 2、当前节点cur放入s2栈内
// 3、压入当前节点左节点、在压入当前节点右节点
// 4、重复1、2、3步骤
if (!root) return []
const s1 = [], s2 = [], res = [];
s1.push(root)
while (s1.length) {
let head = s1.pop()
s2.push(head)
if (head.left) {
s1.push(head.left)
}
if (head.right) {
s1.push(head.right)
}
}
while (s2.length) {
res.push(s2.pop().val)
}
return res
};