在JavaScript中搜索二叉树 [英] Searching a Binary Tree in JavaScript
本文介绍了在JavaScript中搜索二叉树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我对JavaScript有点迷失.我有这个结构:
I am a bit lost in JavaScript. I have this structure:
{
"value": 5,
"children": [{
"value": 18,
"children": [{
"value": 27,
"children": []
}, {
"value": 4,
"children": []
}]
}, {
"value": 2,
"children": []
}]
}
如何使用JavaScript在树中获得最高价值?
How can I get the highest value in the tree using JavaScript?
推荐答案
在这种特定情况下,您可能需要使用以下代码:
In this specific case you'd might want to use this:
var baseObject = {
"value": 5,
"children": [{
"value": 18,
"children": [{
"value": 27,
"children": []
}, {
"value": 4,
"children": []
}]
}, {
"value": 2,
"children": []
}]
};
function getHighestValue(obj) {
var res = obj.value;
for(var i in obj.children) {
res = Math.max(res, getHighestValue(obj.children[i]));
}
return res;
}
alert(getHighestValue(baseObject));
这篇关于在JavaScript中搜索二叉树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文