/*class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @return int整型一维数组
*/
export function postorderTraversal(root: TreeNode): number[] {
const resArr: number[] = []
if (root == null) return resArr
// 解法一:递归
// postOrder(root, resArr)
// 面试官:用非递归解决?
// 解法二:非递归
postOrder2(root, resArr)
return resArr
}
// 解法一:递归函数
// 时间复杂度 O(n)
function postOrder(node: TreeNode, resArr: number[]) {
if (node == null) return
postOrder(node.left, resArr)
postOrder(node.right, resArr)
resArr.push(node.val)
}
// 解法二:非递归函数
// 时间复杂度 O(n)
function postOrder2(root: TreeNode, resArr: number[]) {
const stack1: TreeNode[] = [root]
const stack2: number[] = []
while (stack1.length) {
const top = stack1.pop()
stack2.push(top.val)
// 注意栈先进后出的特点
if (top.left) stack1.push(top.left)
if (top.right) stack1.push(top.right)
}
while (stack2.length) {
resArr.push(stack2.pop())
}
}