java - 在相同标签的 n 叉树中搜索最低(最深层次)节点
问题描述
这是我的 n 叉树的节点类
import java.util.ArrayList;
public class Node{
public String label;
public ArrayList<Node> children;
public Node(String label){
this.label =label;
this.children = new ArrayList<Node>();
}
public void addChild(String child){
Node childNode = new Node(child);
this.children.add(childNode);
}
public void addChild(Node child){
this.children.add(child);
}
public Node findNode(String label){
if(this.label.equals(label))
return this;
for(Node child : this.children)
if (child.findNode(label) != null)
return child.findNode(label);
return null;
}
}
我需要一个像“ Node findNode(String label)
”这样的方法,但给出具有相同标签的最低节点。
此图中的示例
解决方案
修改您
Node.class
以存储另一个变量,int height
当您Tree objectTree
从rootNode
.
rootNode.getHeight()=0 默认情况下。从rootNode
函数 in的简单遍历Node.class
将如下所示:
//note : This assumes you are at any Node. The root Node will have height = 0 ~important
public Node findLabel(String label){
Node tempNode = null;
assert this.getHeight()!=null;
if(this.label.equals(label)){
tempNode = this;
}
//traverse this' children
for(Node child : this.children){
child.setHeight(this.getHeight()+1); //setting children height
Node t = child.findNode(label);
if(t!=null){
if(tempNode!=null){
if(tempNode.getHeight()>t.getHeight()){
tempNode=t;
}
}else{
tempNode=t; //set TempNode = t as tempNode is null as this is our first solution
}
}
}
return tempNode; //can be null and Contains the lowest node in the tree with label
}
推荐阅读
- javascript - 我试图在我的 Wix 网站上的几个页面上隐藏标题。似乎没有办法做到这一点。想法?
- r - 具有多个范围的 if 语句 (R)
- python - 如何在这段代码中使用 pylint(not-an-iterable)?
- regex - 正则表达式:二进制字符串至少包含某个整数的 3 个
- ruby - 如何在 jekyll 网站中添加谷歌翻译插件?
- django - 为什么 django 迁移会暂时占用磁盘空间?
- algorithm - 贪心算法交换证明(算法设计,第 4 章,第 6E 章)
- javascript - 如何在 Nightwatch JS 中对伪元素进行断言
- javascript - 尝试转换 CSV 文件时出现 InvalidStateError
- c++ - 如何让我的程序接受指针?