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": 3
}Execution steps
- Search for deletion
- Replace with successor
- Remove leaf
Computed output
[ 5, 4, 7, 2, null, 6, 8 ]
JavaScript reference implementation
const solve = ({
a,k
},s)=>{
function f(i,k){
if(!exists(a,i))return;
let l=2*i+1,r=l+1;
s("Search for deletion",{
Tree:nodes(a),Current:[i]
});
if(k<a[i])f(l,k);
else if(k>a[i])f(r,k);
else if(exists(a,l)&&exists(a,r)){
let j=r;
while(exists(a,2*j+1))j=2*j+1;
a[i]=a[j];
s("Replace with successor",{
Tree:nodes(a),Current:[i,j]
});
f(r,a[j])
}else if(!exists(a,l)&&!exists(a,r)){
a[i]=null;
s("Remove leaf",{
Tree:nodes(a),Current:[i]
})
}else{
let j=exists(a,l)?l:r;
function move(x,y){
let v=a[x];
a[y]=v??null;
if(v!=null){
move(2*x+1,2*y+1);
move(2*x+2,2*y+2);
a[x]=null
}
}
move(j,i);
s("Promote child",{
Tree:nodes(a),Current:[i]
})
}
}
f(0,k);
while(a.at(-1)==null)a.pop();
return a
};
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
}