Created
June 18, 2012 19:12
-
-
Save bolgovr/2950146 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var Leaf = function (value) { | |
this.right = null; | |
this.left = null; | |
this.value = value || null; | |
}; | |
var Tree = function () { | |
this.root = null; | |
}; | |
Tree.prototype.addLeaf = function (value) { | |
if (this.root === null) { | |
this.root = new Leaf(value); | |
} else { | |
var parent = this.findParent(this.root, value); | |
if (value >= parent.value) { | |
parent.right = new Leaf(value); | |
} else { | |
parent.left = new Leaf(value); | |
} | |
} | |
}; | |
Tree.prototype.findValue = function (tree, value) { | |
if (tree === null) { | |
return null; | |
} else { | |
if (value === tree.value) { | |
return tree; | |
} else if (value >= tree.value) { | |
return this.findValue(tree.right, value); | |
} else if (value < tree.value) { | |
return this.findValue(tree.left, value); | |
} | |
} | |
}; | |
Tree.prototype.findParent = function (tree, value) { | |
if (value >= tree.value) { | |
if (tree.right === null) { | |
return tree; | |
} else { | |
return this.findParent(tree.right, value); | |
} | |
} | |
if (value < tree.value) { | |
if (tree.left === null) { | |
return tree; | |
} else { | |
return this.findParent(tree.left, value); | |
} | |
} | |
}; | |
var fs = require('fs'); | |
var tree = new Tree(); | |
fs.readFile('./source.txt', function (err, content) { | |
var array = content.toString().split('\n').map(function (num) { | |
return parseInt(num, 10); | |
}); | |
array.pop(); //последний \n дает NaN | |
array.forEach(function (num) { | |
tree.addLeaf(num); | |
}); | |
var lookingFor = process.argv.pop(); | |
console.log('looking for ' + lookingFor); | |
array.forEach(function (num) { | |
var part = lookingFor - num; | |
if (part < 0) { | |
return; | |
} | |
if (tree.findValue(tree.root, part)) { | |
console.log('yes'); | |
process.exit(0); | |
} | |
}); | |
console.log('no'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment