【发布时间】:2020-06-01 08:09:37
【问题描述】:
我想想象一下深度优先遍历函数是如何工作的?我正在学习递归,我已经理解了 insert 和 contains 函数。但是当涉及到深度优先遍历时,我无法理解程序的流程?
function bst(value){
this.value = value;
this.left = null;
this.right = null;
};
bst.prototype.insert = function(value){
if(value <= this.value){
if(!this.left) this.left = new bst(value);
else this.left.insert(value);
}
else if (value > this.value){
if(!this.right) this.right = new bst(value);
else this.right.insert(value);
}
};
bst.prototype.contains = function(value){
if (value === this.value) return true;
if (value < this.value){
if(!this.left) return false;
else return this.left.contains(value);
}
if (value > this.value){
if(!this.right) return false;
else return this.right.contains(value);
}
};
bst.prototype.depthFirstTraversal = function(iteratorFunc, order){
if(order === 'pre-order') iteratorFunc(this.value);
if(this.left) this.left.depthFirstTraversal(iteratorFunc, order);
if(order === 'in-order') iteratorFunc(this.value);
if(this.right)this.right.depthFirstTraversal(iteratorFunc, order);
if(order === 'post-order') iteratorFunc(this.value);
};
function log(value){
console.log(value);
}
var mybst = new bst(50);
mybst.insert(40);
mybst.insert(30);
mybst.insert(60);
mybst.insert(10);
mybst.insert(70);
mybst.insert(80);
mybst.insert(55);
console.log(mybst);
console.log(mybst.contains(30));
mybst.depthFirstTraversal(log, "in-order");
【问题讨论】:
标签: javascript recursion data-structures binary-search-tree depth-first-search