在TreeView查找某一节点,通常有两种方法,一种是递归的,一种不是递归,但都是深度优先算法。其中,非递归方法效率高些,而递归算法要简洁一些。
第二种,非递归算法,代码如下:
程序调用,如下:
TreeNode tnRet
=
null
;
foreach ( TreeNode tn in yourTreeView.Nodes )
{
tnRet = FindNode( tn, yourValue );
if ( tnRet != null ) break ;
}
foreach ( TreeNode tn in yourTreeView.Nodes )
{
tnRet = FindNode( tn, yourValue );
if ( tnRet != null ) break ;
}
第一种,递归算法,代码如下:
![](http://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
private TreeNode FindNode( TreeNode tnParent, string strValue )
{
if( tnParent == null ) return null;
if( tnParent.Text == strValue ) return tnParent;
TreeNode tnRet = null;
foreach( TreeNode tn in tnParent.Nodes )
{
tnRet = FindNode( tn, strValue );
if( tnRet != null ) break;
}
return tnRet;