-
Notifications
You must be signed in to change notification settings - Fork 0
/
checkSubTree.js
128 lines (107 loc) · 1.97 KB
/
checkSubTree.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
119
120
121
122
123
124
125
126
127
function Node(data){
this.data = data;
this.left = null;
this.right = null;
}
function BinarySearchTree(){
this.root = null;
}
BinarySearchTree.prototype.insert = function(data){
if(!this.root){
this.root = new Node(data);
}
else {
current = this.root;
while(current){
if(data < current.data){
if(!current.left){
current.left = new Node(data);
return;
}
else{
current = current.left;
}
}
else if(data>current.data){
if(!current.right){
current.right = new Node(data);
return;
}
else{
current = current.right;
}
}
else{//duplicates
return ;
}
}
}
}
function height(node){
if(!node){
return 0;
}
else{
return 1+Math.max(height(node.left), height(node.right));
}
}
function checkSubTree(tree1, tree2){
console.log("***");
var h1 = height(tree1.root);
var h2 = height(tree2.root);
if(h1 > h2){
tree1 = getSubTree(tree1, tree2.root.data);
}
else if(h2 > h1){
tree2 = getSubTree(tree2, tree1.root.data);
}
var h1 = height(tree1);
var h2 = height(tree2);
if(h1 === h2){
for(var i=1;i<=h1;i++){
var list1 = getInorder(tree1.root, i);
var list2 = getInorder(tree2.root, i);
if(list1.toString() !== list2.toString()){
return false;
}
}
return true;
}
return false;
}
function getSubTree(tree, data){
if(!tree.root){
return null;
}
var current = tree.root;
while(current){
if(data === current.data){
tree.root = current;
return tree;
}
else if(data < current.data){
current = current.left;
}
else if(data>current.data){
current = current.right;
}
}
return null;
}
function getInorder(node, height){
if(height === 1){
if(!node){
return null;
}
else{
return node.data;
}
}
var inOrderList =[];
while(height >=1){
height = height -1;
inOrderList = inOrderList.concat(getInorder(node.left,height));
inOrderList = inOrderList.concat(getInorder(node.right,height));
}
return inOrderList;
}