【发布时间】:2015-08-29 06:25:11
【问题描述】:
我在使用 C# 设置子节点时遇到了一些问题。我正在尝试构建一个节点树,其中每个节点都包含一个 int 值,并且最多可以有多个与其值相等的子节点。
当我在一个节点中迭代寻找空(null)子节点时出现了我的问题,以便我可以在该位置添加一个新节点。我可以找到并返回空节点,但是当我将新节点设置为它时,它会失去与父节点的连接。
因此,如果我添加 1 个节点,则它会链接到我的头节点,但如果我尝试添加第二个节点,它不会成为头节点的子节点。我正在尝试使用单元测试来构建它,所以这里的测试代码显示确实头部没有显示新节点,因为它是子节点(也通过 Visual Studio 调试器确认):
[TestMethod]
public void addSecondNodeAsFirstChildToHead()
{
//arange
Problem3 p3 = new Problem3();
p3.addNode(2, p3._head);
Node expected = null;
Node expected2 = p3._head.children[0];
int count = 2;
//act
Node actual = p3.addNode(1, p3._head);
Node expected3 = p3._head.children[0];
//assert
Assert.AreNotEqual(expected, actual, "Node not added"); //pass
Assert.AreNotEqual(expected2, actual, "Node not added as first child"); //pass
Assert.AreEqual(expected3, actual, "Node not added as first child"); //FAILS HERE
Assert.AreEqual(count, p3.nodeCount, "Not added"); //pass
}
这是我的代码。
public class Node
{
public Node[] children;
public int data;
public Node(int value)
{
data = value;
children = new Node[value];
for(int i = 0; i < value; i++)
{
children[i] = null;
}
}
}
public class Problem3
{
public Node _head;
public int nodeCount;
public Problem3()
{
_head = null;
nodeCount = 0;
}
public Node addNode(int value, Node currentNode)
{
if(value < 1)
{
return null;
}
Node temp = new Node(value);
//check head
if (_head == null)
{
_head = temp;
nodeCount++;
return _head;
}
//start at Current Node
if (currentNode == null)
{
currentNode = temp;
nodeCount++;
return currentNode;
}
//find first empty child
Node emptyChild = findEmptyChild(currentNode);
emptyChild = temp;
nodeCount++;
return emptyChild;
}
public Node findEmptyChild(Node currentNode)
{
Node emptyChild = null;
//find first empty child of current node
for (int i = 0; i < currentNode.children.Length; i++)
{
if (currentNode.children[i] == null)
{
return currentNode.children[i];
}
}
//move to first child and check it's children for an empty
//**this causes values to always accumulate on left side of the tree
emptyChild = findEmptyChild(currentNode.children[0]);
return emptyChild;
}
我觉得问题是我试图像在 C++ 中那样将节点视为指针,但它没有按我预期的那样工作。
【问题讨论】:
-
一些调试可能会有所帮助...作为起点 - 你的
findEmptyChild总是返回null- 不太确定你希望从中得到什么。 -
看看这里的答案:stackoverflow.com/questions/66893/… 一般来说,在数组中管理空值不是一个好方法,只需使用
List。 -
Alexei,当我搜索一个孩子时,我想找到第一个空的孩子,这样我就可以将一个节点放入该数组索引中。就像当 head(root) 为 null 时,您将节点分配给 head,我想找到一个 null 子节点并将节点分配给它。但是这样做会在我当前的实现中失去与父级的联系。本质上,我试图将空节点的指针传回,以便我可以为该指针分配一个节点。