2013-08-18 153 views
2

到目前爲止,我已經算出算法來添加到我的二叉搜索樹中,但是我有點難以將它轉換爲代碼。該算法如下:創建二叉搜索樹

public void add(int v) { 
Create a new node n to hold value v. 
    If tree is empty 
     Set root to n. 
    Else 
     Create temporary node reference m, initialized to root. 
     Loop looking for a gap (a null left or right pointer) that is on the 
     correct side of m for v 
      If v < m.value, look at the left pointer 
      If v >= m.value, look at the right pointer 
     If pointer on correct side is not null, set m to that child node and 
     continue looking 
      m = m.left or m = m.right 
    The search for insertion position stops when node m has a null pointer on 
    the correct side. 
    Insert the new node n at that position 
     m.left = n or m.right = n 
} 

到目前爲止,我有:

public void add(int v) { 
     Node n = new Node(v); 
     if(root==null) 
      root = n; 
     else { 
      Node m = root; 
      while(...) { 
       if(...) 
        m = m.left; 
       else 
        m = m.right; 
      } 
      if(...) 
       m.left = m; 
      else 
       m.right = n; 

     } 
    } 

我相信大多數的這是正確的,但我不知道需要做的地方標記爲」什麼。 ..「

+0

我認爲谷歌搜索會產生無數的這個問題的結果。 – Algorithmist

+0

我確實有這個實現(它使用泛型):http://sdrv.ms/19qBooi(看看BinaryTree.java和TreeNode.java) – gparyani

回答

1

首先,二叉搜索樹不應該有任何重複值,這是您在代碼中未實現的重要要求。我最近在學習java中的數據結構時實現了二叉搜索樹。這裏是我寫的代碼:

public class OrderedBinaryTree 
{ 
    private int _elementsPresent = 0; 
    private Node _root = null; 
    private int [] _values = null; 
    private class Node 
    { 
     Node _left = null; 
     Node _right = null; 
     Node _parent = null; 
     int _value = 0; 
     public Node(int value,Node parent) 
     { 
      _value = value; 
      _parent = parent; 
     } 
    } 
    public void put(int value) 
    { 
     boolean valueInserted = false; 
     Node temp = _root; 
     while(!valueInserted) 
     { 
      if(_root == null) 
      { 
       _root = new Node(value,null); 
       break; 
      } 
      else if(value == temp._value) 
      { 
       System.out.println("the entered value is already present"); 
       return; 
      } 
      else if(value<=temp._value) 
      { 
       if(temp._left == null) 
       { 
        temp._left = new Node(value,temp); 
        break; 
       } 
       else 
       { 
        temp = temp._left; 
       } 
      } 
      else 
      { 
       if(temp._right == null) 
       { 
        temp._right = new Node(value,temp); 
        break; 
       } 
       else 
       { 
        temp = temp._right; 
       } 
      } 
     } 
     _elementsPresent++; 
    } 
+1

你不應該檢查布爾是否等於false;相反,您應該在布爾值上使用not('!')運算符。 – gparyani