Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 678def9

Browse files
committed
given range k1, k2. find elements between them
1 parent 5fde75b commit 678def9

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
'use strict';
2+
class Node {
3+
constructor(data) {
4+
this.data = data;
5+
this.leftNode = this.rightNode = null;
6+
}
7+
}
8+
9+
function insertInBST(root, data) {
10+
if (root == null) return new Node(data);
11+
else if (root.data > data) root.leftNode = insertInBST(root.leftNode, data);
12+
else root.rightNode = insertInBST(root.rightNode, data);
13+
return root;
14+
}
15+
16+
function rangeElements(root, k1, k2, resultArr) {
17+
if (root == null) return null;
18+
if (root.data > k1) rangeElements(root.leftNode, k1, k2, resultArr);
19+
if (root.data >= k1 && root.data <= k2) resultArr.push(root.data);
20+
if (root.data < k2) rangeElements(root.rightNode, k1, k2, resultArr);
21+
}
22+
23+
let tree = null;
24+
tree = insertInBST(tree, 4);
25+
tree = insertInBST(tree, 2);
26+
tree = insertInBST(tree, 3);
27+
tree = insertInBST(tree, 1);
28+
tree = insertInBST(tree, 6);
29+
tree = insertInBST(tree, 5);
30+
tree = insertInBST(tree, 7);
31+
// BST
32+
// 4
33+
// / \
34+
// 2 6
35+
// / \ / \
36+
// 1 3 5 7
37+
let k1 = 1, k2 = 6;
38+
let resultArr = [];
39+
rangeElements(tree, k1, k2, resultArr);
40+
console.log('Elements between ' + k1 + ' And ' + k2 + ' are - ' + resultArr.join(', '));

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /