在二叉树中找到一个节点的祖先节点是我们常用的一个算法,今天我们就来介绍两种不同的方式,一种代码简单但是效率较低,用到了递归,另一种代码复杂但是效率较高,利用非递归的后序遍历
递归方式的代码如下
public boolean ancestor(Node node,int x){
if (node==null){
return false;
}
else{
if(node.getData()==x)
return true;
else{
boolean b1=ancestor(node.left,x);
boolean b2=ancestor(node.right,x);
if(b1||b2)
System.out.print(node.getData()+" ");
return b1||b2;
}
}
}
/**
* 给出根节点和一个节点的值,找出这个节点的所有祖先节点并且将他们打印出来(非递归方式)
*/
public void ancestor2(Node node,int x){
Node[] qu=new Node[255];
int flag=0;
int k=0;
Node pre=null;
Node p=node;
if(p!=null){
qu[k++]=p;
p=p.getLeft();
while(k>0){
while(p!=null){
qu[k++]=p;
p=p.left;
}
pre=null;
flag=1;