Fix a few bugs and improve performance with k-ary tree