查找指定节点
使用我们的前中后序遍历找到一个指定节点,查找HeroNode = 4 分别查找了几次?
例子还是我们上面讲到的那个二叉树,我们先分析
前序查找:先判断当前的no是不是要查找的,是就返回当前节点,不是的话,判断当前节点的左子节点是否为空,若不为空则递归前序查找,找到返回,为空(或者没有找到)的话就去判断右子树,跟我们的左子节点一样
emmmm,其他两种都已一样的套路,这里就不多说了
前序遍历:小王——>小胡——>小黄——>老肥找到
中序遍历:小胡——>小王——>老肥找到
后序遍历:小胡——>老肥找到
上代码,我用的还是上次的那个二叉树,我直接贴方法的代码,其他的就不补充了
节点中的遍历查找方法
/**
* 前序遍历查找
* @param no 待查找编号
* @return
*/
public HeroNode preOrderSearch(int no){
//判断当前节点是不是
if(this.no == no){
return this;
}
//判断左子节点是否为空
HeroNode resNode = null;//辅助节点
if(this.left != null){
resNode = this.left.preOrderSearch(no);
}
if(resNode != null){
//说明左子树上找到了
return resNode;
}
if(this.right != null){
resNode = this.right.preOrderSearch(no);
}
return resNode;
}
//中序遍历查找
public HeroNode infixOrderSearch(int no){
HeroNode resNode = null;
//先判断当前节点的左子节点
if(this.left != null){
resNode = this.left.infixOrderSearch(no);
}
if(resNode != null){
return resNode;
}
if(this.no == no){
return this;
}
if(this.right != null){
resNode = this.right.infixOrderSearch(no);
}
return resNode;
}
//后序遍历查找
public HeroNode postOrderSearch(int no){
HeroNode resNode = null;
if(this.left != null){
resNode = this.left.postOrderSearch(no);
}
if(resNode != null){
return resNode;
}
if(this.right != null){
resNode = this.right.postOrderSearch(no);
}
if(resNode != null){
return resNode;
}
if(this.no == no)
return this;
return resNode;
}
树中的遍历查找方法
//前序遍历查找
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;
}
}
测试
//测试查找
System.out.println("-----------------------------");
System.out.println("测试前序遍历查找4号节点");
System.out.println(binnaryTreeDemo.preOrderSearch(4));
System.out.println("-----------------------------");
System.out.println("测试中序遍历查找4号节点");
System.out.println(binnaryTreeDemo.infixOrderSearch(4));
System.out.println("-----------------------------");
System.out.println("测试后序遍历查找4号节点")