Worked example and algorithm walkthrough
Topic: Binary Trees · Structure and paths
Follow the computed execution on the reference input. Advance one step at a time, inspect the changing values and compare your prediction with the final output.
Example input
{
"a": [
1,
2,
3,
4,
5,
null,
6
],
"start": 1,
"k": 2,
"burn": false
}Execution steps
- Expand one distance layer
Computed output
[ 3 ]
JavaScript reference implementation
const solve = ({
a,start,k,burn
},s)=>{
let q=[start],seen=new Set(q),d=0;
while(q.length){
s("Expand one distance layer",{
Tree:nodes(a),Frontier:q,Visited:[...seen],Distance:[d]
});
if(!burn&&d===k)return q.map(i=>a[i]);
let next=[];
for(let i of q)for(let j of [Math.floor((i-1)/2),2*i+1,2*i+2])if(j>=0&&exists(a,j)&&!seen.has(j)){
seen.add(j);
next.push(j)
}
q=next;
d++
}
return burn?d-1:[]
};
function exists(a,i){
return i<a.length&&a[i]!=null
}
function nodes(a){
return a.map((v,i)=>v==null?null:[i,v,exists(a,2*i+1)?2*i+1:null,exists(a,2*i+2)?2*i+2:null]).filter(Boolean)
}
function ordered(a,s,mode){
let o=[];
function f(i){
if(!exists(a,i))return;
if(mode==="pre"){
o.push(a[i]);
s("Visit node before children",{
Tree:nodes(a),Visited:o,Current:[i]
})
}
f(2*i+1);
if(mode==="in"){
o.push(a[i]);
s("Visit node between children",{
Tree:nodes(a),Visited:o,Current:[i]
})
}
f(2*i+2);
if(mode==="post"){
o.push(a[i]);
s("Visit node after children",{
Tree:nodes(a),Visited:o,Current:[i]
})
}
}
f(0);
return o
}