一颗树.怎么遍历拿某一节点的相关信息,
一,可以foreach硬写,一直遍历,知道满足条件,在外部定义一个变量接受.
优点是比较好阅读,按从上到下的逻辑下,缺点就是代码量较多,不够优雅
二.用递归
写递归,先想好退出条件
没有的时候返回空,满足条件的时候,返回传进来的节点的信息
还有就是没有子节点时,递归的返回结果节点不为空,组合返回,
函数的最后返回一个默认为空
public (string noPath,string nodeNamePath) GetPath(Class root,string targetNo)
{
if(root == null)
return (string.Empty,string.Empty);
if(root.No == targetNo)
return (root.No,root.NodeName);
while(root.Childrens !=null)
{
foreach(var childrenItem in root.Childrens)
{
var (noPath,nodeNamePath) = GetPath(childrenItem,targetNo);
if(!string.IsNullOrEmpty)
return ($"{root.No}/{noPath}",$"{root.NodeName}/{nodeNamePath}");
}
}
return (string.Empty,string.Empty);
}
在不理解的情况下,默写代码,真的有用,我这段代码已经记下来了.