標籤:
本題來自《劍指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實現