二叉樹的深度(遞迴和非遞迴)---java實現__二叉樹

來源:互聯網
上載者:User

遞迴實現

為了求樹的深度,可以先求其左子樹的深度和右子樹的深度,可以用遞迴實現,遞迴的出口就是節點為空白。傳回值為0;

非遞迴實現

利用層次遍曆的演算法,設定變數level記錄當前節點所在的層數,設定變數last指向當前層的最後一個節點,當處理完當前層的最後一個節點,讓level指向+1操作。設定變數cur記錄當前層已經訪問的節點的個數,當cur等於last時,表示該層訪問結束。

層次遍曆在求樹的寬度、輸出某一層節點,某一層節點個數,每一層節點個數都可以採取類似的演算法。

樹的寬度:在樹的深度演算法基礎上,加一個記錄訪問過的層節點個數最多的變數max,在訪問每層前max與last比較,如果max比較大,max不變,如果max小於last,把last賦值給max;

代碼:

import java.util.LinkedList;public class Deep{//遞迴實現1  public int findDeep(BiTree root)  {  int deep = 0;  if(root != null)  {  int lchilddeep = findDeep(root.left);  int rchilddeep = findDeep(root.right);  deep = lchilddeep > rchilddeep ? lchilddeep + 1 : rchilddeep + 1;  }  return deep;  }      //遞迴實現2  public int findDeep1(BiTree root)  {  if(root == null)  {  return 0;  }  else  {   int lchilddeep = findDeep1(root.left);//求左子樹的深度   int rchilddeep = findDeep1(root.left);//求右子樹的深度   return lchilddeep > rchilddeep ? lchilddeep + 1 : rchilddeep + 1;//左子樹和右子樹深度較大的那個加一等於整個樹的深度  }  }      //非遞迴實現  public int findDeep2(BiTree root)  { if(root == null) return 0; BiTree current = null; LinkedList<BiTree> queue = new LinkedList<BiTree>(); queue.offer(root); int cur,last; int level = 0; while(!queue.isEmpty()) { cur = 0;//記錄本層已經遍曆的節點個數 last = queue.size();//當遍曆完當前層以後,隊列裡元素全是下一層的元素,隊列的長度是這一層的節點的個數 while(cur < last)//當還沒有遍曆到本層最後一個節點時迴圈 { current = queue.poll();//出隊一個元素 cur++; //把當前節點的左右節點入隊(如果存在的話) if(current.left != null) { queue.offer(current.left); } if(current.right != null) { queue.offer(current.right); } } level++;//每遍曆完一層level+1 } return level;  }  public static void main(String[] args) {BiTree root = BiTree.buildTree();Deep deep = new Deep();System.out.println(deep.findDeep(root));System.out.println(deep.findDeep1(root));System.out.println(deep.findDeep2(root)); }}
樹的結構

                   A

             /              \

           B               C

         /    \                 \

       D     E               G


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.