/*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 inorderTraversal(root: TreeNode): number[] {
const resArr: number[] = []
if (root == null) return resArr
// 解法一:递归
// inOrder(root, resArr)
// 面试官:用非递归解决?
// 解法二:非递归
inOrder2(root, resArr)
return resArr
}
// 解法一:递归函数
// 时间复杂度 O(n)
function inOrder(node: TreeNode, resArr: number[]) {
if (node == null) return
inOrder(node.left, resArr)
resArr.push(node.val)
inOrder(node.right, resArr)
}
// 解法二:非递归函数
// 时间复杂度 O(n)
function inOrder2(root: TreeNode, resArr: number[]) {
let node: TreeNode = root
const stack: TreeNode[] = []
while (stack.length || node) {
while (node) {
stack.push(node)
node = node.left
}
const top = stack.pop()
resArr.push(top.val)
node = top.right
}
}