数据结构中的BST add()方法

时间:2016-04-03 21:11:17

标签: java data-structures

我只需要一点方向来解决这个数据结构问题。我必须为BST创建一个add()方法。我知道如何对这个问题进行递归解决,但是什么是非递归解决方案呢?这是我的班级。

import java.util.*;

public class BST 
{
// instance variables
private BSTNode m_root;
private int m_size;

// constructor
public BST()
{
    m_root = null;
    m_size = 0;
}

// add a value into the tree

    public void add(int v)
{   BSTNode current = m_root;
    if(current == null) {
    m_root=new BSTNode(v);
    m_size++;
    }
    else
    {
    while(current!=null) {
    if(current.getInfo() > v) {
    if(current.getLeft() == null) {
    m_root.setLeft(new BSTNode(v));
    m_size++;
    current=null;
    }
    else
    current = current.getLeft();

    }
    else if(current.getInfo()< v) {
    if(current.getRight() == null) {
    m_root.setRight(new BSTNode(v));
    current=null;
    m_size++;
    }
    else current = current.getRight();
}}}}

// get the size of the tree
public int size()
{
    return m_size;
}

// empty the tree
public void clear()
{
    m_root = null;
    m_size = 0;
}
}

2 个答案:

答案 0 :(得分:1)

想出来!

  public void add(int v)
    { BSTNode current = m_root;
    if(current == null) {
    m_root=new BSTNode(v);
    m_size++;

    }
    else
    {
    while(current!=null) {
    if(current.getInfo()==v)
    {current=null;}
    else if(current.getInfo() > v) {
    if(current.getLeft() == null) {
    m_root.setLeft(new BSTNode(v));
    m_size++;
    current=null;
    }
    else
    current = current.getLeft();

    }
    else if(current.getInfo()< v) {
    if(current.getRight() == null) {
    m_root.setRight(new BSTNode(v));
    current=null;
    m_size++;
    }
    else current = current.getRight();
    }}
    }
    }

答案 1 :(得分:0)

BSTNode current = m_root;
if(current == null) {
    current = new BSTNode(v);
    return;
}
while(true) {
    if(current.key > v) {
        if(current.left == null) {
            current.left = new BSTNode(v);
            break;
        }
        else
            current = current.left;
    }
    else if(current.key < v) {
        if(current.right == null) {
            current.right = new BSTNode(v);
            breakl;
        }
        else current = current.right;
    }
}