腾讯前端试题
腾讯前端试题
昨天做了下腾讯的前端试题,最后一个题目,找出一个类二叉树的最大的和(每一层取一个数字)。

本来这个树只有12层,心算也可以计算出来。
但是,当时硬是就没算出来。。。心一横,还是写个程序算吧。
于是就有了以下的代码:
1. 定义一个类,有两个方法,可以计算最大的和,以及找出最大和对应的路径。(最后加了一句,可以直接模拟点击)
function node(v){
this.value = v;
this.left = null;
this.right = null;
}
node.prototype.getMax = function(){
if (null == this.left)
this.m = this.value;
else {
var l = this.left.getMax(), r = this.right.getMax();
this.m = l > r ? l + this.value : r + this.value;
this.next = l > r ? this.left : this.right;
}
return this.m;
}
node.prototype.getRoad = function() {
console.log(this.value);
$this = this;$this.obj.click();
if (this.next) setTimeout(function(){ $this.next.getRoad();}, 1000);
}
2. 遍历所有的节点生成二叉树
var data = [], rootDom = document.getElementById('box'), list = rootDom.getElementsByTagName('span');
for (var i = 0, r = 1, n = 1; i < list.length; i++, n++)
{
console.log('(' + r + ', ' + n + ') : ' + i +' --> ' + list.item(i).innerText)
if (!data[r]) data[r] = [];
data[r][n] = new node(parseInt(list.item(i).innerText));
data[r][n].obj = list.item(i);
if (r > 1 && n > 1) data[r-1][n-1].right = data[r][n];
if (r > 1 && n < r) data[r-1][n].left = data[r][n];
if (n == r)
{
r++;
n = 0;
}
}
3. 计算最大值,并找出路径。
console.log(data[1][1].getMax()); data[1][1].getRoad()

浙公网安备 33010602011771号