-
Notifications
You must be signed in to change notification settings - Fork 71
/
No144.binary-tree-preorder-traversal.js
118 lines (109 loc) · 2.28 KB
/
No144.binary-tree-preorder-traversal.js
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
/**
* Difficulty:
* Medium
*
* Desc:
* Given a binary tree, return the preorder traversal of its nodes' values.
*
* Example:
* Given binary tree [1,null,2,3],
1
\
2
/
3
* return [1,2,3].
*
* Note:
* Recursive solution is trivial, could you do it iteratively?
*
* 前序遍历树:根左右
*/
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/* ============================ Recursive Solution ============================ */
/**
* @param {TreeNode} root
* @return {number[]}
*/
var preorderTraversal_recursive = function(root) {
const result = [];
const preorder = (node) => {
if (!node) return;
result.push(node.val);
preorder(node.left);
preorder(node.right);
};
preorder(root);
return result;
};
/* ============================ Iteratively Solution ============================ */
/**
* @param {TreeNode} root
* @return {number[]}
*/
const preorderTraversal_iteratively = (root) => {
if (!root) return []
const queue = [root]
const result = []
while (queue.length) {
const node = queue.pop()
result.push(node.val)
if (node.right) queue.push(node.right)
if (node.left) queue.push(node.left)
}
return result
}
/**
* @param {TreeNode} root
* @return {number[]}
*/
const preorderTraversal_iteratively_2 = (root) => {
const queue = []
const result = []
let node = root
while (node || queue.length) {
if (node) {
result.push(node.val)
queue.push(node)
node = node.left
} else {
node = queue.pop()
node = node.right
}
}
return result
}
/* ============================ Morris Traversal Solution ============================ */
/**
* @param {TreeNode} root
* @return {number[]}
*/
var preorderTraversal_mirror = function(root) {
let prev = null
let node = root
const result = []
while (node) {
if (!node.left) {
result.push(node.val)
node = node.right
} else {
prev = node.left
while (prev.right && prev.right !== node) prev = prev.right
if (!prev.right) {
prev.right = node
result.push(node.val)
node = node.left
} else {
prev.right = null
node = node.right
}
}
}
return result
}