我在树上通过递归找某一节点,
返回值为TreeNode,
当找到符合要求的节点后能立刻终止递归,返回得到的值么?

解决方案 »

  1.   

    private TreeNode FindNode( TreeNode tnParent, string strText )
    {
       if( tnParent == null ) return null;
       
       if( tnParent.Text == strText ) return tnParent;   TreeNode tnResult = null;
       foreach( TreeNode tn in tnParent.Nodes )
       {
            tnResult = FindNode( tn, strText );
            if( tnResult != null ) return tnResult;
       }
       return null;
    }
      

  2.   

    Knight94(愚翁) 
    解释的已经很好了
      

  3.   

    当然可以不用递归来实现,如
    private TreeNode FindNode( TreeNode  tnParent, string strValue )
    {
    if( tnParent == null ) return null; if( tnParent.Text == strValue ) return tnParent;
    else if( tnParent.Nodes.Count == 0 ) return null; TreeNode tnCurrent, tnCurrentPar; tnCurrentPar = tnParent;
    tnCurrent = tnCurrentPar.FirstNode; while( tnCurrent != null && tnCurrent != tnParent )
    {
    while( tnCurrent != null )
    {
    if( tnCurrent.Text == strValue ) return tnCurrent;
    else if( tnCurrent.Nodes.Count > 0 ) 
    {
    tnCurrentPar = tnCurrent;
    tnCurrent = tnCurrent.FirstNode;
    }
    else if( tnCurrent != tnCurrentPar.LastNode )
    {
    tnCurrent = tnCurrent.NextNode;
    }
    else
    break;
    }
    while( tnCurrent != tnParent && tnCurrent == tnCurrentPar.LastNode )
    {
    tnCurrent = tnCurrentPar;
    tnCurrentPar = tnCurrentPar.Parent;
    } if( tnCurrent != tnParent )
    tnCurrent = tnCurrent.NextNode;
    }
    return null;
    }