how can you build binary tree without sorting it, I.E
if i have a input 5 4 9 8 1 2 7 how can you insert that into a reference based binary tree. I know this can be easily implemented with Array, but is it possible with reference base?
how can you build binary tree without sorting it, I.E
if i have a input 5 4 9 8 1 2 7 how can you insert that into a reference based binary tree. I know this can be easily implemented with Array, but is it possible with reference base?
One simple rule is to always insert into the left subtree and then switch the subtrees. The right subtree will always be 0-1 elements larger than the left subtree, so you can always insert into the left subtree. Now, the left subtree is 0-1 elements larger than the right subtree, so you want to switch the subtrees to preserve the invariant. In pseudocode:
insert(t,v) {
if (t == null) {
return new TreeNode(v,null,null)
} else {
left = insert(t.left,v)
right = t.right
t.left = right
t.right = left
return t
}
}