LeetCode-144. Binary Tree Preorder Traversal

问题描述

Given the root of a binary tree, return the preorder traversal of its nodes’ values.

Constraints:

  • The number of nodes in the tree is in the range [0, 100].
  • -100 <= Node.val <= 100

解答

方法一:递归
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/*
* @Description: 144. Binary Tree Preorder Traversal
* @Author: libk
* @Github: https://github.com/libk
*/
/**
* 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)
* }
*/
/**
* @description: 递归写法一
* @param {TreeNode} root
* @return {number[]}
*/
const preorderTraversal = function (root) {
if (!root) {
return []
}
return [root.val, ...preorderTraversal(root.left), ...preorderTraversal(root.right)]
}

/**
* @description: 递归写法二
* @param {TreeNode} root
* @return {number[]}
*/
const preorderTraversal1 = function (root) {
let res = []
const visitLoop = (root) => {
if (root) {
res.push(root.val)
visitLoop(root.left)
visitLoop(root.right)
}
}
visitLoop(root)
return res
}
方法二:迭代
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/*
* @Description: 144. Binary Tree Preorder Traversal
* @Author: libk
* @Github: https://github.com/libk
*/
/**
* 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)
* }
*/
/**
* @description: 非递归
* @param {TreeNode} root
* @return {number[]}
*/
const preorderTraversal2 = function (root) {
let stack = []
let res = []
let cur = root
while (cur || stack.length) {
if (cur) {
stack.push(cur)
res.push(cur.val)
cur = cur.left
} else {
cur = stack.pop()
cur = cur.right
}
}
return res
}