gpt4 book ai didi

javascript - 在 JavaScript 中搜索二叉树

转载 作者:行者123 更新时间:2023-11-28 08:10:45 25 4
gpt4 key购买 nike

我对 JavaScript 有点迷失了。我有这样的结构:

{
"value": 5,
"children": [{
"value": 18,
"children": [{
"value": 27,
"children": []
}, {
"value": 4,
"children": []
}]
}, {
"value": 2,
"children": []
}]
}

如何使用 JavaScript 获取树中的最高值?

最佳答案

在这种特定情况下,您可能需要使用它:

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));

http://jsfiddle.net/qc9R4/1/

关于javascript - 在 JavaScript 中搜索二叉树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24262304/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com