请大家帮我看下这个TreeView遍历算法有何隐患?

大狗狗 2009-03-02 09:56:24
不怕错,就怕曾经对而现在错。昨天关机前还用的好好的算法,今早起来就出了问题(代码没改,机器系统不变)


请大家帮我看下这个TreeView遍历算法有什么隐患?该算法特点是没有用到Stack

public static bool traverse(TreeNodeCollection node, RichTextBox edit)
{
if ((node == null) || (node.Count == 0))
{
return false;
}

TreeNode temp = node[0];

edit.Text = "";

while (temp != null)
{
while (temp.Nodes.Count > 0)
{
temp = temp.Nodes[0];
}

edit.Text += temp.Text;
edit.Text += "\r\n";

if (temp.NextNode != null)
{
temp = temp.NextNode;
}
else
{
temp = temp.Parent;
if (temp == null)
{ break; }

edit.Text += temp.Text;
edit.Text += "\r\n";

temp = temp.NextNode;
}

}//end while

return true;
}//end fun
...全文
80 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
大狗狗 2009-03-04
  • 打赏
  • 举报
回复
感谢各位回贴,特别感谢javabegin ,针对性地找出了偶的问题所在!
linlin1972 2009-03-02
  • 打赏
  • 举报
回复
while (temp.Nodes.Count > 0)
{
temp = temp.Nodes[0];
}

当某个中间层次有多个节点时只会处理第一个节点。修改的方法...好象除了递归,没有更合适的方法了。

:-)

不知道说的对不对。
javabegin 2009-03-02
  • 打赏
  • 举报
回复
有问题。例如树形结构如下:
A
-A1
-A11
-A2
-A21
B
-B1
-B11

当你遍历到A21时(即temp=A21,),执行下面代码

temp = temp.Parent;
if (temp == null)
{ break; }

edit.Text += temp.Text;
edit.Text += "\r\n";

temp = temp.NextNode;



当执行“temp = temp.Parent;” 时temp值变为A2,
然后执行“ temp = temp.NextNode;”,这时候temp值(也就是A2.NextNode)为null;按常理这时应该返回到A2.Parent再去遍历,但是你没有返回到A2的Parent。
按你的代码执行结果就是:
A11
A1
A21
A2
连根节点A都没有遍历到。你这个只能遍历A的所有子节点。
建议用递归算法,或者如你所说用堆栈来遍历。
Roc_Lee 2009-03-02
  • 打赏
  • 举报
回复
没有问题,空看代码,有点问题,厉害厉害
JaggerLee 2009-03-02
  • 打赏
  • 举报
回复
LZ想让你猜呀,空军
wuyi8808 2009-03-02
  • 打赏
  • 举报
回复
[Quote=引用楼主 Win32FanEx 的帖子:]
不怕错,就怕曾经对而现在错。昨天关机前还用的好好的算法,今早起来就出了问题(代码没改,机器系统不变)


请大家帮我看下这个TreeView遍历算法有什么隐患?该算法特点是没有用到Stack

public static bool traverse(TreeNodeCollection node, RichTextBox edit)
{
if ((node == null) || (node.Count == 0))
{
return false;
}


[/Quote]

什么问题?

111,126

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Creator Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧