Binary Tree insertion (in order sorted)

笑着哭i 提交于 2019-12-03 22:02:00

Inserting into a zero-element tree is easy:

return tree_make(elt, tree_make(), tree_make());

Inserting into a one-element tree is also easy:

tree_t new_node = tree_make(elt, tree_make(), tree_make());
if(elt < tree_elt(tree))
    return tree_make(tree_elt(tree), new_node, tree_right(tree));
else
    return tree_make(tree_elt(tree), tree_left(tree), new_node);

In general, to insert a new element, you'll need to recreate all of its parents in this manner.


Part 2: Recursion

We have our base case (a zero-element tree). And we know how to attach a new subtree to the root of our existing tree.

So how to get the new subtree? Well, how about we just insert the element into the current subtree?

The following code will always attach the new element at the far left of the tree, but that should be trivial to correct once you understand it:

tree_t tree_insert(int elt, tree_t tree)
{
    if(tree_empty(tree)) //base case
        return tree_make(elt, tree_make(), tree_make());
    else
        return tree_make( // make a new node
            tree_elt(tree) // with the same value as the current one
            tree_insert(elt, tree_left(tree)) //insert into the left subtree
            tree_right(tree) // keep the right subtree the same
            );
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!