前序查找
//前序遍历查找
public HeroNode preOrderSeach(int no) {
System.out.println("前序遍历");
if(this.no == no) {//比较当前节点
return this;
}
//判断当前节点的左子节点是否为空
//如果左递归前序查找 找到节点 则返回
HeroNode res = null;//结果节点
if(this.left!=null) {
res = this.left.preOrderSeach(no);//递归前序查找
}
if(res != null) {//不为空说明查找到了 为空则右递归前序查找
return res;
}
//1.左递归前序查找,找到结点,则返回,否继续判断,
//2.当前的结点的右子节点是否为空,如果不空,则继续向右递归前序查找
if(this.right != null) {
res = this.right.preOrderSeach(no);
}
return res;
}
中序查找
//中序遍历查找
public HeroNode infixOrderSearch(int no) {
//判断当前结点的左子结点是否为空 不会空进行递归中序查找
HeroNode resHeroNode = null;
if(this.left != null) {
resHeroNode = this.left.infixOrderSearch(no);
}
if(resHeroNode != null) {
return resHeroNode;
}
//如果找到,则返回,如果没有找到,就和当前结点比较,如果是则返回当前结点
System.out.println("中序遍历");
if(this.no == no) {
return this;
}
//否则进行右递归中序查找
if(this.right != null) {
resHeroNode = this.right.infixOrderSearch(no);
}
return resHeroNode;
}
后序查找
//后序遍历查找
public HeroNode postOrderSearch(int no) {
//判断当前结点的左节点是否为空 不为空进行递归后序查找
HeroNode resHeroNode = null;
if(this.left != null) {
resHeroNode = this.left.postOrderSearch(no);
}
if(resHeroNode!=null) {
return resHeroNode;
}
//左子树没找到 找右子
if(this.right != null) {
resHeroNode = this.right.postOrderSearch(no);
}
if(resHeroNode != null) {
return resHeroNode;
}
//左右子树都没找到
System.out.println("后序遍历");
if(this.no == no) {
return this;
}
return resHeroNode;
}