How to add elements in Binary search tree iteratively?

℡╲_俬逩灬. 提交于 2019-12-19 10:56:29

问题


   public void Insert(int value)
    {
        if (value < Data)
        {
            if (LeftNode == null)
            {
                LeftNode = new TreeNode(value);
            }
            else
            {
                LeftNode.Insert(value);
            }
        }
        else if (value > Data)
        {
            if (RightNode == null)
            {
                RightNode = new TreeNode(value);
            }
            else
            {
                RightNode.Insert(value);
            }
        }
    }

I wrote method to add element in BST recursively, It checks for value to add less than or greater than and add it in its proper place, but I want to know how iterative method works? I need iterative add method for my BST.


回答1:


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();
}



回答2:


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;
    }
}



回答3:


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.



来源:https://stackoverflow.com/questions/8383976/how-to-add-elements-in-binary-search-tree-iteratively

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