列印二叉樹中一個節點的所有祖先節點
阿新 • • 發佈:2019-01-24
在二叉樹中找到一個節點的祖先節點是我們常用的一個演算法,今天我們就來介紹兩種不同的方式,一種程式碼簡單但是效率較低,用到了遞迴,另一種程式碼複雜但是效率較高,利用非遞迴的後序遍歷
遞迴方式的程式碼如下
這是非遞迴方式,其實只是後序遍歷的一個簡單應用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; while(flag==1&&k>0){ p=qu[k-1]; if(p.right==pre){ k--; if(p.data==x){ for(int i=0;i<=k;i++){ System.out.print(qu[i].getData()+" "); } } pre=p; } else{ p=p.right; flag=0; } } } } }