日期:2014-05-18  浏览次数:20464 次

一个递归的疑问
各位请指教,我下面这个递归有什么问题?  

 private TreeNode FindNodeInTree(TreeNode objTreeNode, string strNodeData)
  {
  foreach (TreeNode tn in objTreeNode.ChildNodes)
  {
  if (tn.Value != strNodeData)
  {

  FindNodeInTree(tn, strNodeData);
  }
  else
  {
  //ExpandTree2(tn);
  return tn;
  }
  }
  return null;
  }

------解决方案--------------------
if (tn.Value != strNodeData)
{

FindNodeInTree(tn, strNodeData); // 假如刚好在这个内部递归找到的值的时候,你外部调用者会得到值的吗?
}
------解决方案--------------------
TreeNode targetNode = FindNodeInTree(...);
if(targetNode != null) {
// ....
} else {
//...
}



private TreeNode FindNodeInTree(TreeNode objTreeNode, string strNodeData)
{
foreach (TreeNode tn in objTreeNode.ChildNodes)
{
if (tn.Value != strNodeData)
{

TreeNode tmpNode = FindNodeInTree(tn, strNodeData);
if(tmpNode != null) return tmpNode;
}
else
{
//ExpandTree2(tn);
return tn;
}
}
return null;
}