LeetCode general Solution for BST In Order Traverse

In Order Traverse

There are a quite few leet code questions that is based on BST traverse.Here is a general template that could be used to solve similar problems.The idea is using a set to store the intermediate result.
The solution is in javascript.

LeetCode 94

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

//Definition for a binary tree node.
var treeNode = function(val) {
this.val = val;
this.left = this.right = null;
}

var inOrderTraverse = function (root) {

let list = [];
let stack = [];

if (root == null) {

return true;
}

while (root != null || stack.length > 0) {
while (root != null) {
stack.push(root);
root = root.left;
}
root = stack.pop();
list.push(root.val);
root = root.right;
}

return list;
}

LeetCode 230

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
var kthSmallest = function(root, k) {

let stack = [];
let list = [];

if (root == null) {
return true;
}

while (root != null || stack.length > 0) {

while (root != null) {

stack.push(root);
root = root.left;
}

root = stack.pop();
list.push(root.val);
if (list.length == k) {
return root.val;
}
root = root.right;
}
};

LeetCode 98

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
var isValidBST = function(root) {

let stack = [];
//let list = [];

if (root === null) {
return true;
}

let prev = null;

while (root !== null || stack.length > 0) {

while (root !== null) {

stack.push(root);
root = root.left;
}

root = stack.pop();

if (prev != null && root.val <= prev.val) {

return false
};

prev = root;
//list.push(root.val);
root = root.right;
}

return true;
};


  TOC