Worked example and algorithm walkthrough
Topic: Binary Search Trees · Ordering and operations
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": [
5,
3,
7,
2,
4,
6,
8
],
"k": 9
}Execution steps
- Choose insertion branch
- Insert leaf
Computed output
[ 5, 3, 7, 2, 4, 6, 8, null, null, null, null, null, null, null, 9 ]
JavaScript reference implementation
const solve = ({
a,k
},s)=>{
let i=0;
while(exists(a,i)){
s("Choose insertion branch",{
Tree:nodes(a),Current:[i],Target:[k]
});
i=2*i+(k<a[i]?1:2)
}
a[i]=k;
s("Insert leaf",{
Tree:nodes(a),Current:[i]
});
return Array.from(a,x=>x??null)
};
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
}