Amazon Interview Question
Backend DevelopersCountry: United States
in javascript:
{{
function node(dat){
this.data = dat;
this.left = null;
this.right = null;
}
node.prototype.insert = function(dat){
if (this.data >= dat){
if(!this.left)
this.left = new node(dat);
else
this.left.insert(dat);
} else{
if (!this.right)
this.right = new node(dat);
else
this.right.insert(dat);
}
}
node.prototype.get = function(dat){
if (this.data === dat) return this;
if (this.data >= dat && this.left) return this.left.get(dat);
if (this.data < dat && this.right) return this.right.get(dat);
return null;
};
let size = 0;
node.prototype.size = function(){
size++;
if (this.left) this.left.size();
if (this.right) this.right.size();
}
function createTree(nNode){
let myTree = new node(nNode);
let dat;
for(i=1;i<nNode;i++){
dat = Math.floor(Math.random() * (1000-100)) + 100;
//console.log(dat);
myTree.insert(dat)
}
return myTree;
}
let myTree = createTree(734);
myTree.size();
console.log("Size:", size);
}}
Duplicate from here :
- NoOne March 07, 2018[ careercup.com/question?id=5701069362429952 ]