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
[ 3, 1, 4, null, null, 2 ]
Execution steps
- Detect inorder inversion
- Restore swapped values
Computed output
[ 2, 1, 4, null, null, 3 ]
JavaScript reference implementation
const solve = (a,s)=>{
let prev=-1,x=-1,y=-1;
function f(i){
if(!exists(a,i))return;
f(2*i+1);
if(prev>=0&&a[prev]>a[i]){
if(x<0)x=prev;
y=i
}
s("Detect inorder inversion",{
Tree:nodes(a),Current:[i],Swapped:[x,y]
});
prev=i;
f(2*i+2)
}
f(0);
if(x>=0)[a[x],a[y]]=[a[y],a[x]];
s("Restore swapped values",{
Tree:nodes(a)
});
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
}