コードの最後に、.getChildren関数を定義したノードのインスタンスを2つ作成しますが、Uncaught TypeError: t2.getChildren is not a function
が得られます。また、なぜt2ではなくt1でこれを言っているのですか?2つのオブジェクト、1つは「関数ではない」
function Node(value) {
// based on graph theory, we give
this.value = value;
this.children = [];
this.parent = null;
// set and get functions
this.setParent = function(node) {
this.parent = node;
};
this.getParent = function() {
return this.parent;
};
this.addChild = function(node) {
node.setParent(this);
this.children[this.children.length] = node;
};
this.getChildren = function() {
return this.children;
};
}
// check Identical
var subTreeFinder = function (t1,t2) {
// base cases
if (t2==null) {
return true; // empty trees are subtrees to all trees
}
if (t1==null){
return false; // a non-empty tree can't fit in an empty tree
}
if (checkIdentical(t1,t2)) {
return true;
}
var t1Children = t1.getChildren();
var t2Children = t2.getChildren();
return subTreeFinder(t1Children.every(subTreeFinder) || t2Children.every(subTreeFinder));
}
// check Identical
var checkIdentical = function (t1,t2) {
// base case
if (t1==null && t2 == null) {
return true;
}
if (t1 != null && t2 != null) {
var t1Children = t1.getChildren();
var t2Children = t2.getChildren();
// an obvious case and time saver
if (t1Children.length != t2Children.length){
return false;
}
// recursive call. for every arr. element in both sets of kids check if we recurrsively get back true
if (t1.value == t2.value && t1Children.every(checkIdentical) && t2Children.every(checkIdentical)) {
return true;
}
}
// here: either one is null and the other ins't, so false.
return false;
}
// The actual Trees
var dom = new Node('a'); // root
dom.addChild(new Node('b'));
dom.addChild(new Node('c'));
var vdom = new Node('x'); // root
vdom.addChild(new Node('y'));
vdom.addChild(new Node('z'));
console.log(subTreeFinder(dom, vdom));
// console.log(dom); // Should read entire Demo Tree object (unfold to see contents)
を修正しました。 –