好吧,我有这个二叉树,我写它的方式是方程式在树外,它工作但我需要知道如何在树中存储方程并使用遍历函数计算...任何建议将非常感谢。
var node = {
value: 125,
left: null,
right: null,
};
function BinarySearchTree() {
this._root = null;
}
BinarySearchTree.prototype = {
constructor: BinarySearchTree,
add: function(value) {
var node = {
value: value,
left: null,
right: null
},
current;
if (this._root === null) {
this._root = node;
} else {
current = this._root;
while (true) {
if (value < current.value) {
if (current.left === null) {
current.left = node;
break;
} else {
current = current.left;
}
} else if (value > current.value) {
if (current.right === null) {
current.right = node;
break;
} else {
current = current.right;
}
} else {
break;
}
}
}
},
traverse: function(process) {
function postOrder(node) {
if (node) {
if (node.left !== null) {
postOrder(node.left);
}
if (node.right !== null) {
postOrder(node.right);
}
process.call(this, node);
}
}
postOrder(this._root);
},
toArray: function() {
var result = [];
this.traverse(function(node) {
result.push(node.value);
});
return result;
},
toString: function() {
return this.toArray().toString();
}
};
function calculate(element) {
var x = document.getElementById("xvalue").value;
var y = document.getElementById("yvalue").value;
x = parseInt(x, 10);
y = parseInt(y, 10);
var answer = 3 * (x + 5 * y);
document.getElementById("output").innerHTML = "3 * (x + 5 * y) = " + answer;
}
&#13;
X:
<input type="text" name="x" id="xvalue" value="1"> Y:
<input type="text" name="y" id="yvalue" value="1">
<input type="button" id="b1" value="Click Here" onclick="calculate(this)" />
<p id="output"></p>
&#13;