2011-02-25 34 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;