Searching A Binary Tree In Javascript
Solution 1:
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": []
}]
};
functiongetHighestValue(obj) {
var res = obj.value;
for(var i in obj.children) {
res = Math.max(res, getHighestValue(obj.children[i]));
}
return res;
}
alert(getHighestValue(baseObject));
Solution 2:
if understand you correct should look something like this.
var highestValue = JSONresponse.value;
HighVal(JSONresponse);
functionHighVal(JSON)
{
if(highestValue < JSON.value)
{
highestValue = JSON.value
}
for(i=0;i<JSON.children.lenght;i++)
{
HighVal(JSON.children[i]);
}
}
Solution 3:
Another way of doing this, if your object tree pattern is the same,
Stringify object and do regular expression to fetch all the integer values of this pattern "value: {n}" and then find the max value.
var jsono = {
"value": 5,
"children": [{
"value": 18,
"children": [{
"value": 27,
"children": []
}, {
"value": 4,
"children": []
}]
}, {
"value": 2,
"children": []
}]
}
var maxvalue;
JSON.stringify(jsono).match(/\"value\":\s*(\d+)/g).map(function(value){ return value.match(/(\d+)/g).map(function(value){ maxvalue = Math.max(maxvalue || 0,value);});});
alert(maxvalue);
Solution 4:
I won't write the code for you, but basically, it's the same with any other language.
You traverse through every right child until you know that it's the end node.
How to use JavaScript to access JSON?
var tree =
{
parent : [
{
//child1 details
},
{
//child2 details
},
]
}
For JSON key access, use tree.<key> (dot)
or tree['key']
. In this case, tree.parent
or tree["parent"]
.
For Array access, use indices. Since parent
is an array, you can access the children by tree.parent[0]
or tree['parent'][0]
.
I prefer the dot method though, to distinguish visually JSONs and arrays.
Also, you need something to distinguish a right child and a left child. You can either make it a convention to make the right child as the [0]
index in the array, or you can add another value per node that says that its right or left.
Post a Comment for "Searching A Binary Tree In Javascript"