2013-05-05 65 views
1

我已经在C#中编写了用于实现AVL_trees的代码。我遇到了一些节点问题,这就是为什么我无法在节点中插入数据的原因。以下是我的代码。无法在avl_tree中添加节点

public class avl_node 
{ 
    public int Data; 
    public avl_node Left; 
    public avl_node Right; 
    public int height; 

    public void DisplayNode() 
    { 
     Console.Write("{0}", Data); 
    } 
} 



public class avl_tree 
{ 
    public avl_node root; 

    public avl_tree() 
    { 
     root = null; 
    } 

    public void Insert(int i) 
    { 
     avl_node newNode = new avl_node(); 
     newNode.Data = i; 
     newNode.height = newNode.height + 1; 
     if (root == null) 
     { 
      root = newNode; 
     } 
     else 
     { 
      avl_node current = root; 
      avl_node parent; 
      while (true) 
      { 
       parent = current; 
       if (i < current.Data) 
       { 
        current = current.Left; 
        if (current == null) 
        { 
         parent.Left = newNode; 
         break; 
        } 
        else 
        { 
         current = current.Right; 
         if (current == null) 
         { 
          parent.Right = newNode; 
          break; 
         } 
        } 
       } 
      } 
     } 
    } 


    public void InOrder(avl_node node) 
    { 
     if (!(node == null)) 
     { 
      InOrder(node.Left); 
      node.DisplayNode(); 
      InOrder(node.Right); 
     } 
    } 
} 



class Program 
{ 
    static void Main(string[] args) 
    { 
     avl_tree nums = new avl_tree(); 
     nums.Insert(23); 
     nums.Insert(45); 
     nums.Insert(16); 
     nums.Insert(37); 
     nums.Insert(3); 
     nums.Insert(99); 
     nums.Insert(22); 
     avl_node nd = new avl_node(); 
     nd = nums.Search(37); 

     Console.WriteLine("Inorder traversal: "); 
     nums.InOrder(nums.root); 
    } 
} 

我得到的只是一个黑色的控制台屏幕。我很困扰。

希望能有更好的回应。

问候 乌默尔

+0

你的'Search'函数是什么样的?如果你在主函数的每一行之间放置打印语句,哪一行会停止? – Xymostech 2013-05-05 00:31:13

+0

@Xymostech忘记搜索功能。我忘了评论该行。由于整个代码已被注释掉,该行对程序没有影响!我不知道为什么我无法在控制台窗口上获得任何东西! – 2013-05-05 00:41:17

回答

1

“我得到的是一个黑色的控制台屏幕”

23后插入,你插入()方法被卡在while循环,因为45是从未小于23 :

 while (true) 
     { 
      parent = current; 
      if (i < current.Data) 
       // you never get in here, so we just loop around in "while (true)" 
1

看看在插入方法循环,​​你会得到卡在循环每次尝试插入任何值比树已经存在的价值更大。

它会因为这个条件而发生:if(i < current.data)。 else语句在哪里?你把它放在提到的条件范围内。所以它永远不会被达到,因此程序将运行无限循环。

您应该在else语句之前放置一个“}”,否则将会超出第一个if语句的范围。并在方法结尾处删除“}”中的一个。

这样它应该运行得很好。