原题链接
typescript
function preorderTraversal(root: TreeNode | null): number[] {
let current = root;
const stack: TreeNode[] = [];
const answer: number[] = [];
while(current || stack.length) {
while(current) {
answer.push(current.val);
stack.push(current);
current = current.left;
}
if(stack.length) {
current = stack.pop();
current = current.right;
}
}
return answer;
};