/**
* 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 = []
let dfs = function () {
if (!root) return []
if (root.left) { dfs(root.left) }
if (root.right) { dfs(root.right) }
res.push(root.val)
}
return res
};
// 时间复杂度O(n),n为节点个树,空间复杂度O(n),显示栈的空间开销
// 后续遍历:左右中
// 压栈顺序:中右左
// var postorderTraversal = function(root, res = []) {
// const stack = [];
// if (root) stack.push(root);
// while(stack.length) {
// const node = stack.pop();
// if(!node) {
// res.push(stack.pop().val);
// continue;
// }
// stack.push(node); // 中
// stack.push(null);
// if (node.right) stack.push(node.right); // 右
// if (node.left) stack.push(node.left); // 左
// };
// return res;
// };