1个回答
展开全部
下面代码随手写的,未运行验证,大概是这样的,只提供个思路,要运行的话,自己调试下,能不能弄懂,就看你自己的了
/**
* TreeNode.java
* 二叉树节点
*/
public Class TreeNode {
public String val; //当前值
public TreeNode lChild;
public TreeNode rChild;
public TreeNode(){}
public TreeNode(String val) {
this.val = val;
}
}
/**
* TestMain.java
* 主测试程序
*/
public Class TestMain {
private TreeNode root; //树根节点
public void TestMain() {
//初始化树
root = new TreeNode("S");
//S的左儿子A
TreeNode tna = new TreeNode("A");
root.lChild = tn;
//A的左儿子A1
TreeNode tna1 = new TreeNode(“A1”);
tna.lChild = tna1;
//A的右儿子A2
TreeNode tna2 = new TreeNode("A2");
tna.rChild = tna2;
//S的右儿子B
TreeNode tnb = new TreeNode("B");
root.rChild = tnb;
}
//查找树接口
public TreeNode findWithVal(String nodeVal) {
return findNode(root, nodeVal);
}
//递归查找子树
private TreeNode findNode(TreeNode rtNode, String nodeVal) {
if(nodeVal == null) { //查找对象不能为空
throw new RuntimeException("nodeVal can't be null");
}
if(rtNode == null) { //当前结点为空,表示不在此分支中
return null;
} else if(rtNode.val.equals(nodeVal)) { //找到结点
return this;
} else { //当前结点不是要找的结点,在子树中查找
TreeNode resNode = findNode(rtNode.lChild, nodeVal); //在左分支(儿子)中查找
if(resNode == null) { //不在左分支中
resNdoe = findNode(rtNode.rChild, nodeVal); //在右分支中查找
}
return resNode; //返回查找结果,如果不在当前结点的子结点中,则返回空,如果存在则返回该节点对象;
}
}
public static void main(<很久不写主函数了,参数怎么写不记得了>) {
TestMain testMain = new TestMain();
if(testMain.findWithVal("A1") != null) {
System.out.println("找到结点");
} else {
System.out.println("节点未找到");
}
}
}
/**
* TreeNode.java
* 二叉树节点
*/
public Class TreeNode {
public String val; //当前值
public TreeNode lChild;
public TreeNode rChild;
public TreeNode(){}
public TreeNode(String val) {
this.val = val;
}
}
/**
* TestMain.java
* 主测试程序
*/
public Class TestMain {
private TreeNode root; //树根节点
public void TestMain() {
//初始化树
root = new TreeNode("S");
//S的左儿子A
TreeNode tna = new TreeNode("A");
root.lChild = tn;
//A的左儿子A1
TreeNode tna1 = new TreeNode(“A1”);
tna.lChild = tna1;
//A的右儿子A2
TreeNode tna2 = new TreeNode("A2");
tna.rChild = tna2;
//S的右儿子B
TreeNode tnb = new TreeNode("B");
root.rChild = tnb;
}
//查找树接口
public TreeNode findWithVal(String nodeVal) {
return findNode(root, nodeVal);
}
//递归查找子树
private TreeNode findNode(TreeNode rtNode, String nodeVal) {
if(nodeVal == null) { //查找对象不能为空
throw new RuntimeException("nodeVal can't be null");
}
if(rtNode == null) { //当前结点为空,表示不在此分支中
return null;
} else if(rtNode.val.equals(nodeVal)) { //找到结点
return this;
} else { //当前结点不是要找的结点,在子树中查找
TreeNode resNode = findNode(rtNode.lChild, nodeVal); //在左分支(儿子)中查找
if(resNode == null) { //不在左分支中
resNdoe = findNode(rtNode.rChild, nodeVal); //在右分支中查找
}
return resNode; //返回查找结果,如果不在当前结点的子结点中,则返回空,如果存在则返回该节点对象;
}
}
public static void main(<很久不写主函数了,参数怎么写不记得了>) {
TestMain testMain = new TestMain();
if(testMain.findWithVal("A1") != null) {
System.out.println("找到结点");
} else {
System.out.println("节点未找到");
}
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询