/*
* @lc app=leetcode.cn id=144 lang=typescript
*
* [144] 二叉树的前序遍历
*/
// @lc code=start
/**
* Definition for a binary tree node.
* 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)
* }
* }
*/
interface TreeNode {
val: number
left: TreeNode | null
right: TreeNode | null
}
function preorderTraversal(root: TreeNode | null): number[] {}
// @lc code=end
- 时间复杂度:
- 空间复杂度:
function preorderTraversal(root: TreeNode | null): number[] {
if (!root) return []
return [root.val].concat(preorderTraversal(root.left)).concat(preorderTraversal(root.right))
}
- 时间复杂度:
- 空间复杂度:
function preorderTraversal(root: TreeNode | null): number[] {
const stack: Array<TreeNode> = [],
nums: Array<number> = []
while (root || stack.length) {
if (root) {
nums.push(root.val)
stack.push(root)
root = root.left
} else {
root = stack.pop()!.right
}
}
return nums
}
- 时间复杂度:
- 空间复杂度:
function preorderTraversal(root: TreeNode | null): number[] {
const nums: Array<number> = []
while (root) {
if (!root.left) {
nums.push(root.val)
root = root.right
} else {
let pre = root.left
while (pre.right !== null && pre.right !== root) {
pre = pre.right
}
if (pre.right === null) {
nums.push(root.val)
pre.right = root
root = root.left
} else {
pre.right = null
root = root.right
}
}
}
return nums
}
test.each([
{ input: { root: [1, null, 2, 3] }, output: [1, 2, 3] },
{ input: { root: [] }, output: [] },
{ input: { root: [1] }, output: [1] },
{ input: { root: [1, null, 2] }, output: [1, 2] },
])('input: root = $input.root', ({ input: { root }, output }) => {
expect(preorderTraversal(BinaryTree.deserialize(root))).toEqual(output)
})