Last active
August 29, 2015 13:56
-
-
Save making/8795733 to your computer and use it in GitHub Desktop.
javascriptで2分木
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
// http://jsfiddle.net/L6bfa | |
var TreeNode = function (value, left, right) { | |
this.value = value; | |
this.left = left; | |
this.right = right; | |
}; | |
var Tree = function (root) { | |
this.root = root; | |
}; | |
Tree.prototype.leftTree = function () { | |
return new Tree(this.root.left); | |
}; | |
Tree.prototype.rightTree = function () { | |
return new Tree(this.root.right); | |
}; | |
Tree.prototype.contains = function (value) { | |
if (!this.root) { | |
return false; | |
} else if (this.root.value == value) { | |
return true; | |
} else if (value > this.root.value) { | |
return this.rightTree().contains(value); | |
} else { | |
return this.leftTree().contains(value); | |
} | |
}; | |
Tree.prototype.insert = function (value) { | |
if (this.root.value <= value) { | |
if (this.root.right) { | |
this.rightTree().insert(value); | |
} else { | |
this.root.right = new TreeNode(value); | |
} | |
} else { | |
if (this.root.left) { | |
this.leftTree().insert(value); | |
} else { | |
this.root.left = new TreeNode(value); | |
} | |
} | |
return this; | |
}; | |
var n4 = new TreeNode(4, null, null), | |
n7 = new TreeNode(7, null, null), | |
n9 = new TreeNode(9, null, null), | |
n8 = new TreeNode(8, n7, n9), | |
n5 = new TreeNode(5, n4, n8), | |
root = n5, | |
tree = new Tree(root); | |
tree.insert(3).insert(10); | |
console.log(tree); | |
for (var i = 1; i <= 10; i++) { | |
console.log(i, tree.contains(i)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment