-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathbinary-tree-inorder-traversal.js
More file actions
81 lines (74 loc) · 1.72 KB
/
binary-tree-inorder-traversal.js
File metadata and controls
81 lines (74 loc) · 1.72 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
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
// Recursive Solution
var inorderTraversal = function (root) {
if (root === null) {
return [];
}
var ret = [];
inorderTraversalBuilder(root, ret);
return ret;
};
function inorderTraversalBuilder(root, ret) {
if (root === null) {
return;
}
inorderTraversalBuilder(root.left, ret);
ret.push(root.val);
inorderTraversalBuilder(root.right, ret);
}
// Iterative Solution
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
/*
1) Create an empty stack S.
2) Initialize current node as root
3) Push the current node to S and set current = current->left until current is NULL
4) If current is NULL and stack is not empty then
a) Pop the top item from stack.
b) Print the popped item, set current = popped_item->right
c) Go to step 3.
5) If current is NULL and stack is empty then we are done.
*/
var inorderTraversal = function (root) {
if (root === null) {
return [];
}
var ret = [];
var stack = [root];
var cur = root;
while (stack.length > 0) {
if (cur && cur.left) {
cur = cur.left;
stack.push(cur);
} else {
if (stack.length > 0) {
var temp = stack.pop();
ret.push(temp.val);
cur = temp.right;
if (cur) {
stack.push(cur);
}
}
}
}
return ret;
};