How to add elements in Binary search tree iteratively?

跟風遠走 提交于 2019-12-01 13:00:53

You can find a implementation in Java at wikipedia, what is very similar C# http://en.wikipedia.org/wiki/Binary_search_tree

We start at root:

Node root = m_root;
    while (root != null) {

then look if the value is less os greater than root.

if (data < root.getData()) {

Now we know if we need to traverse at left or right. The logic at left and right are the same. We look if the slot is empty and if it is, we put the value at that slot.

if (root.getLeft() == null) {
    root.setLeft(new TreeNode(data, null, null));
    return;
}

If the slot contains a value, then we set that slot as root and continue the process.

} else {
    root = root.getLeft();
}

Ok, here's an iterative version of your algorithm:

public void Insert(int value)
{
    TreeNode current = this;
    while (current != null)
    {
        if(current.Data < value)
            if(current.LeftNode == null)
            { current.LeftNode = new TreeNode(value); break; }
            else current = current.LeftNode;
        else
            if(current.RightNode == null)
            { current.RightNode = new TreeNode(value); break; }
            else current = current.RightNode;
    }
}

An iterative method is one that will repeat.

Iterative method implies it will be called repeatedly. Recursion implies the method will call itself n times, where n > 0.

Searching a binary search tree is done using a method which calls itself (recursive) until it finds the end of a branch.

To do an insert, a search is executed to find the correct place to place the node.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!