二叉树的查找
先要了解二叉树的构成和创建1个二叉树
链接: 二叉树的遍历(前序遍历,后序遍历,中序遍历)
前序查找
思路:
1.先判断当前节点的no值是否等于要查找的。
如果相等,则直接返回当前节点
2.如果不相等,则判断判断左子节点是否为null,如果不为null,则直接递归左子树。
3.如果左递归找到了,就直接返回,如果没有找到,就递归右子树。
代码:
//前序查找
public HeroNode preOrderSearch(int no){
//先比较当前的节点是不是
if(this.no == no){
//如果是 直接返回
return this;
}
//否则递归左子树继续遍历
HeroNode heroNode = null;
if(this.left != null){
heroNode = this.left.preOrderSearch(no);
}
//说明在左子树中找到了
if(heroNode != null){
return heroNode;
}
//在左子树中没找到,就继续去右子树找
if(this.right != null){
heroNode = this.right.preOrderSearch(no);
}
//如果都没有找到的话返回的就是null
return heroNode;
}
中序查找
思路:
1.判断当前节点的左子节点是否为null,如果不为null,则递归左子树。
2.如果找到,就直接返回,没有找到,就去和当前节点(root)的no进行比较,如果相等就返回当前的节点。否则递归右子树
3.在右子树中找到,就直接返回,没找到就返回null。
代码:
//中序查找
public HeroNode infixSearch(int no){
HeroNode heroNode = null;
//先比较左子树中是否存在
if(this.left != null){
heroNode = this.left.infixSearch(no);
}
//找到就直接返回
if(heroNode != null){
return heroNode;
}
//接着判断当前节点
if(this.no == no){
return this;
}
//接着分析右子树
if(this.right != null){
heroNode = this.right.infixSearch(no);
}
//如果都没有找到的话返回的就是null
return heroNode;
}
后序查找
思路:
1.判断当前的左子节点是否为null,如果不为null,就递归左子树进行查找。
2.如果找到了,就直接返回。没有找到就判断右子节点是否为null,如果不为null,就直接递归右子树进行查找。
3.如果找到了,就直接返回,否则就去和当前节点(root)的no进行比较,如果相等就返回当前的节点。不相等就返回null。
代码:
//后序查找
public HeroNode postSearch(int no){
HeroNode heroNode = null;
//先判断左子树是不存在该值
if(this.left != null){
heroNode = this.left.postSearch(no);
}
if(heroNode != null){
return heroNode;
}
//再去看右子树
if(this.right != null){
heroNode = this.right.postSearch(no);
}
if(heroNode != null){
return heroNode;
}
//最后去找根节点
if(this.no == no){
return this;
}
return heroNode;
}