-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathNo94.binary-tree-inorder-traversal.js
More file actions
100 lines (92 loc) · 2.02 KB
/
Copy pathNo94.binary-tree-inorder-traversal.js
File metadata and controls
100 lines (92 loc) · 2.02 KB
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
/**
* Difficulty:
* Medium
*
* Desc:
* Given a binary tree, return the inorder traversal of its nodes' values.
*
* Example:
* Given binary tree [1,null,2,3],
* 1
\
2
/
3
return [1,3,2].
*
* 求二叉树中序遍历各个元素的顺序
*/
/**
* Note:
* 理解中序遍历:
* 对于每一个树节点,总是先遍历其左子节点,然后遍历根节点,最后右子节点
*/
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/* ============================ Recursive Solution ============================ */
/**
* @param {TreeNode} root
* @return {number[]}
*/
const inorderTraversal_recursive = (root) => {
const result = [];
if (!root) return result;
if (root.left) {
result.push(...inorderTraversal_recursive(root.left));
}
result.push(root.val);
if (root.right) {
result.push(...inorderTraversal_recursive(root.right));
}
return result;
};
/* ============================ Iteratively Solution ============================ */
const inorderTraversal_iteratively = (root) => {
const queue = []
const result = []
let node = root
while (node || queue.length) {
if (node) {
queue.push(node)
node = node.left
} else {
node = queue.pop()
result.push(node.val)
node = node.right
}
}
return result
}
/* ============================ Morris Traversal Solution ============================ */
/**
* @param {TreeNode} root
* @return {number[]}
*/
var inorderTraversal_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
node = node.left
} else {
prev.right = null
result.push(node.val)
node = node.right
}
}
}
return result
}