1

I'm working on an assignment where I have to implement these two methods( add() and inOrder() ).

The code below is what I have so far. What I need help with is adjusting the code to work. Currently, it does not do what I want it to.

add() will only add up to 3 levels on the tree, after that it will just change the 3rd level's nodes. I'm not sure how to write the code for it to go past 3 levels.

inOrder() does not work. When I run, it just stops and prints nothing and forces me to stop running.

Let me know if you need more information.

add():

public void add(int v)
{
    // TODO: implement this method using a non-recursive solution
    BSTNode newNode = new BSTNode(v);
    BSTNode current = m_root;
    if(m_root == null)
    {
        m_root = newNode;
        m_size++;
    }
    else if(v < m_root.getInfo())
    {
        if(m_root.getLeft() == null)
        {
           m_root.setLeft(newNode);
           m_size++;
        }
        else if(m_root.getLeft() != null)
        {
           if(v < m_root.getLeft().getInfo())
           {
              m_root.getLeft().setLeft(newNode);
              m_size++;
           }
           else if(v > m_root.getLeft().getInfo())
           {
              m_root.getLeft().setRight(newNode);
              m_size++;
           }
        }
    }
    else if(v > m_root.getInfo())
    {
        if(m_root.getRight() == null)
        {
           m_root.setRight(newNode);
           m_size++;
        }
        else if(m_root.getRight() != null)
        {
           if(v > m_root.getRight().getInfo())
           {
              m_root.getRight().setRight(newNode);
              m_size++;
           }
           else if(v < m_root.getRight().getInfo())
           {
              m_root.getRight().setLeft(newNode);
              m_size++;
           }
        }
    }
}

inOrder():

// print the tree content using in-order traveral
public void inOrder()
{   
    // TODO: implement this method using a non-recursive solution
    BSTNode current = m_root;
    Stack<BSTNode> stack = new Stack<BSTNode>();
    while(true)
    {
        if(current != null)
        {
           stack.push(current);
           //current = m_root.getLeft();
           m_root.setLeft(current);
           //current.setLeft(current.getLeft());
        }
        else
        {
           if(stack.isEmpty())
           {
              break;
           }
           //stack.pop();
           System.out.println(stack.pop());
           m_root.setLeft(current);
           //current = m_root.getLeft();
           //current.getRight();
        }
    }
}
william h
  • 47
  • 5

0 Answers0