2011-02-25 67 views
0

我想在二叉搜索樹的所有節點中添加深度。這是我的Add方法。但我看到我的深度屬性設置任意值。有人可以讓我知道我犯了什麼錯誤。深度屬性未在BST中設置正確的值

public void Add(int data) 
    { 
     BNode current = root; 
     int depth = 0;   
     while (true) 
     { 
      if (data < (int)current.Data && current.Left != null) 
      { 
       depth = depth + 1; 
       current = current.Left; 
      } 
      else if (data < (int)current.Data && current.Left == null) 
      { 
       depth = depth + 1; 
       current.Left = new BNode(data); 
       current.Left.Parent = current; 
       current.Depth = depth; 
       break; 
      } 
      else if (data > (int)current.Data && current.Right != null) 
      { 
       depth = depth + 1; 
       current = current.Right; 
      } 
      else if (data > (int)current.Data && current.Right == null) 
      { 
       depth = depth + 1; 
       current.Right = new BNode(data); 
       current.Right.Parent = current; 
       current.Right.Depth = depth; 
       break; 
      } 
     } 
    } 

回答

0

對不起,大家好,我找到了我的錯誤。

而不是

current.Depth = depth; 

應該

current.Left.Depth = depth;