二叉树查找指定结点
查找方式分为三种:
- 前序查找
- 中序查找
- 后续查找
代码实现一下~
class HeroNode{
// 1 前序查找
public HeroNode preOrderSearch(int no){
System.out.println("前序查找");
HeroNode temp = null; // 定义一个存储结点
if (this.no == no){
return this; // 比较当前结点,找到则返回
}
if (this.left != null){
temp = this.left.preOrderSearch(no); // 向左递归
}
if (temp != null){
return temp; // 左递归过程中如果不为null则返回查询的结果
}
if (this.right != null){
temp = this.right.preOrderSearch(no); // 进行右递归
}
return temp;
}
// 2 中序查找
public HeroNode infixOrderSearch(int no){
HeroNode temp = null;
if (this.left != null){
temp = this.left.infixOrderSearch(no); // 向左递归
}
if (temp != null){
return temp; // 向左递归时找到了
}
System.out.println("中序查找");
if (this.no == no){
return this; // 判断当前结点是否满足条件
}
if (this.right != null){
temp = this.right.infixOrderSearch(no); // 如果右边还有则向右递归
}
return temp; // 返回结果
}
// 3 后续查找
public HeroNode postOrderSearch(int no){
HeroNode temp = null;
if (this.left != null){
temp = this.left.postOrderSearch(no); // 左递归
}
if (temp != null){
return temp;
}
if (this.right != null){
temp = this.right.postOrderSearch(no); // 右递归
}
if (temp != null){
return temp; // 返回
}
System.out.println("后序查找");
if (this.no == no){
return this;
}
return temp;
}
}
注意:
-
需要注意打印语句的位置,让它在判断语句之前出现,否则有些无效的递归也会输出它(有些递归仅仅是进入下一次递归,并没有进行与结点的比较)
-
在
HashTable
中调用HeroNode
里面提供的方法!
// HashTable中提供的查找
// 前序查找
public HeroNode preOrderSearch(int no){
if (root != null){
return root.preOrderSearch(no);
}else {
return null;
}
}
// 中序查找
public HeroNode infixOrderSearch(int no){
if (root != null){
return root.infixOrderSearch(no);
}else {
return null;
}
}
// 中序查找
public HeroNode postOrderSearch(int no){
if (root != null){
return root.postOrderSearch(no);
}else {
return null;
}
}