问题描述
|
拥有一棵树(DB中的逻辑),其中包含以下形式的项目
清单A
清单B
清单C
清单D
清单项目E
清单项目F
清单项目G
依此类推(嵌套深度不受限制),我想从任意节点开始向下(或向上)下一个节点。
假设,给定
List Item D
,我想编写一个函数GetNextNode()
,该函数将返回List Item E
。
我的想法是做一些递归操作,但是也许有更聪明的方法来处理这个问题?
我的问题:
您将如何解决?
编辑1:
可以使用以下功能访问该树:
GetParentNode()
GetChildrenNodes()
GetNextSiblingNode()
等等
因此类似于e Windows窗体TreeView
。
解决方法
我不得不做几次。从记忆里:
public Node GetBelowNode()
{
if (GetChildrenNodes().count > 0)
return GetChildrenNodes()[0];
else
if (GetNextSiblingNode() != null)
return GetNextSiblingNode();
else
{
Node curr = this;
Node parent;
while (true)
{
parent = curr.GetParentNode();
if (parent == null)
return null;
else
{
if (parent.GetNextSiblingNode() != null)
return parent.GetNextSiblingNode();
else
curr = parent;
}
}
}
}
,您可以通过递归或...处理最差的xD
我认为只有3种基本情况:
private string getNext(TreeNode node)
{
if (node.FirstNode != null)
{
return node.FirstNode.Name;
}
else
{
if (node.NextNode != null)
{
return node.NextNode.Name;
}
else if (node.Parent.NextNode != null)
{
return node.Parent.NextNode.Name;
}
}
return \"\";
}
这并非在所有情况下都适用。您也应该搜索父级的下一个节点。感谢Vincent Vancalbergh的评论;-)
,public Party Next {
get {
if (this.children.Count > 0) return this.children[0];
Party target = this;
do {
if (target.NextSibling != null) return target.NextSibling;
} while ((target = target.Parent) != null);
return null;
}
}
public Party Previous {
get {
if (Parent != null && Parent.children.Count > 0 && this == Parent.children[0]) {
return Parent;
}
Party target = this;
do {
if (target.PreviousSibling != null) { target = target.PreviousSibling; break; }
} while ((target = target.Parent) != null);
if (target != null) {
while (target.children.Count > 0) {
target = target.children[target.children.Count - 1];
}
}
return target;
}
}
,由于我对\“ down \”部分的反应很好,因此我将添加自己的\“ up \”部分。也许是为了您的帮助;上部类似于:
获取上一个同级。
如果存在先前的同级,则获取此节点的最深子节点
兄弟。
如果没有先前的同级,则获取直接父级。
为了获得最深的同级(2.),我使用以下代码:
function getDeepestChild( page )
dim result
set result = nothing
dim childPages
set childPages = page.ChildPages
if childPages.Count>0 then
dim p
set p = childPages(childPages.Count-1)
\' recurse.
set result = getDeepestChild( p )
else
set result = page
end if
set getDeepestChild = result
end function
(是的,我确实知道这是VBScript;实际上我需要用这种语言来编写它)
,试试这个也许:
TreeNode currentNode = treeView1.SelectedNode;
treeView1.selectedNode = currentNode.NextNode;