題目:輸入一棵二叉樹和一個整數,打印出二叉樹中結點值的和爲輸入整數的全部路徑。從根節點開始往下一直到葉節點所通過的節點造成一條路徑。java
解題思路:當使用前序遍歷的方式訪問某一節點時,把該節點添加到路徑上,並累積該節點的數值。若是該節點爲葉節點,而且路徑中節點的值等於輸入的整數,則找到符合條件的路徑。若是當前節點不是葉節點,則繼續遞歸訪問它的子節點。當前節點訪問完遞歸函數回到它的父結點,所以要將當前節點從路徑中刪除,而且當前路徑的和減去當前節點的值。node
package Solution; import java.util.Stack; public class No25PathInTree { public static class BinaryTreeNode { int value; BinaryTreeNode left; BinaryTreeNode right; public BinaryTreeNode(int value, BinaryTreeNode left, BinaryTreeNode right) { super(); this.value = value; this.left = left; this.right = right; } } public static void main(String[] args) { BinaryTreeNode node5 = new BinaryTreeNode(2, null, null); BinaryTreeNode node3 = new BinaryTreeNode(3, null, null); BinaryTreeNode node4 = new BinaryTreeNode(4, null, node5); BinaryTreeNode node7 = new BinaryTreeNode(2, null, null); BinaryTreeNode node2 = new BinaryTreeNode(2, node3, node4); BinaryTreeNode node6 = new BinaryTreeNode(6, node7, null); BinaryTreeNode root1 = new BinaryTreeNode(1, node2, node6); System.out.println("在路徑中查詢值爲9的路徑:"); findPath(root1, 9); System.out.println("在路徑中查詢值爲15的路徑:"); findPath(root1, 15); } private static void findPath(BinaryTreeNode node, int expectedSum) { if (node == null) return; // 保存路徑 Stack<Integer> stack = new Stack<Integer>(); // 記錄當前路徑上節點的和 int currentSum = 0; findPath(node, stack, expectedSum, currentSum); } public static void findPath(BinaryTreeNode node, Stack<Integer> stack, int expectedSum, int currentSum) { if (node == null) return; currentSum += node.value; stack.push(node.value); // 當前節點若是爲葉節點,判斷結點值的和是否爲所要查詢的值 if (node.left == null && node.right == null) { if (currentSum == expectedSum) { // 棧的結構相似於ArrayList,因此遍歷棧會從棧底到棧頂的順序訪問棧中的元素 for (Integer trace : stack) { System.out.print(trace + ","); } System.out.println(); } } if (node.left != null) { findPath(node.left, stack, expectedSum, currentSum); } if (node.right != null) { findPath(node.right, stack, expectedSum, currentSum); } // 當前節點訪問結束後遞歸函數會返回它的父結點,因此在函數退出以前在路徑上刪除當前節點,並減去當前結點的值 // 因爲參數傳遞中傳遞了當前結點參與運算的值,因此在函數退出當前棧幀後,currentSum會恢復成原來的值 stack.pop(); } }