2023年6月22日发(作者:)
如何C#中实现在TreeView查找某⼀节点(两种⽅法)在TreeView查找某⼀节点,通常有两种⽅法,⼀种是递归的,⼀种不是递归,但都是深度优先算法。其中,⾮递归⽅法效率⾼些,⽽递归算法要简洁⼀些。
第⼀种,递归算法,代码如下: private TreeNode FindNode( TreeNode tnParent, string strValue ) { if( tnParent == null ) return null; if( == strValue ) return tnParent;
TreeNode tnRet = null; foreach( TreeNode tn in ) { tnRet = FindNodeExt( tn, strValue ); if( tnRet != null ) break; } return tnRet; }
第⼆种,⾮递归算法,代码如下: private TreeNode FindNode( TreeNode tnParent, string strValue ) { if( tnParent == null ) return null;
if( == strValue ) return tnParent; else if( == 0 ) return null;
TreeNode tnCurrent, tnCurrentPar;
//Init node tnCurrentPar = tnParent; tnCurrent = ode;
while( tnCurrent != null && tnCurrent != tnParent ) { while( tnCurrent != null ) { if( == strValue ) return tnCurrent; else if( > 0 ) { //Go into the deepest node in current sub-path tnCurrentPar = tnCurrent; tnCurrent = ode; } else if( tnCurrent != de ) { //Goto next sible node tnCurrent = de; } else break; } //Go back to parent node till its has next sible node while( tnCurrent != tnParent && tnCurrent == de ) { tnCurrent = tnCurrentPar; tnCurrentPar = ; }
//Goto next sible node if( tnCurrent != tnParent ) tnCurrent = de; } return null; }
程序调⽤,如下: TreeNode tnRet = null; foreach( TreeNode tn in ) { tnRet = FindNodeExt( tn, yourValue ); if( tnRet != null ) break; }
发布者:admin,转转请注明出处:http://www.yc00.com/xiaochengxu/1687382464a5908.html
评论列表(0条)