二叉樹中和為某一值得路徑 java實現

來源:互聯網
上載者:User

標籤:

本題來自《劍指offer》

  路徑為從根節點到分葉節點一條路徑,路徑經過的各節點數值之和等於某一給定數值,則列印路徑上的節點

  • 因為需要列印滿足條件的路徑節點資訊和各節點之和,需要棧記錄經過的節點,和一個儲存數值之和的變數
  • 用前序走訪方法,可以首先訪問節點,然後將節點入棧,並將數值和之前入棧的節點值相加
  • 如果當前之和否滿足給定值,判斷當前節點是否分葉節點,是則列印路徑資訊
  • 判斷節點左右孩子是否為空白,遞迴調用
  • 在調用完,返回時要將入棧的值出棧(此時棧中節點只到父節點),和變數也要變回調用之前的狀態
  •   

     1     //二叉樹定義 2     class Btree { 3         int value; 4         Btree leftBtree; 5         Btree rightBtree; 6     } 7     private Stack<Integer> stack = new Stack<Integer>();  8     public void FindPath(Btree node , int sum,int currSum){ 9         boolean isLeaf;10         if(node == null)11             return;12         currSum += node.value;13         stack.push(node.value);14         isLeaf = node.leftBtree == null && node.rightBtree == null;15         if(currSum == sum && isLeaf){16             System.out.println("Path:");17             for(int val : stack){18                 System.out.println(val);19             }20         }21         if(node.leftBtree != null)22             FindPath(node.leftBtree, sum, currSum);23         if(node.rightBtree != null)24             FindPath(node.rightBtree, sum, currSum);25         currSum -= node.value;26         stack.pop();27     }

     

 

二叉樹中和為某一值得路徑 java實現

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.