問題描述:
輸入一棵二叉樹和一個整數,打印出二叉樹中結點指的和爲輸入整數的所有路徑。從樹的根結點開始往下一直到葉結點所經過的結點形成一條路徑。二叉樹結點的定義如下:
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
思路:利用前序遍歷二叉樹,並藉助一個棧來存儲根到葉子節點的路徑,對每個節點,先檢查當前節點是否是葉子節點,若是則打印路徑。否則看它的左子樹是否爲空,不爲空則遞歸的檢查,此時新的和值應該加上當前節點的值。同樣的右子樹也是一樣。
代碼如下:未經過驗證。
public class FindPath {
void findPath(TreeNode root, int expectedSum){
if(root == null){
return;
}
Stack<Integer> path = new Stack<Integer>();
int currentSum = 0;
findPath(root, expectedSum, path, currentSum);
}
void findPath(TreeNode root, int eS, Stack<Integer> path, int cS){
cS += root.data;
path.push(root.data);
boolean isLeaf = (root.left == null && root.right == null);
//若當前結點不是葉子結點,且當前路徑中的和爲所給和值,則打印出該路徑
if(cS == eS && isLeaf){
for(int i = 0; i < path.size(); i++){
System.out.print(path.get(i)+" ");
}
System.out.println();
}
//若左子樹不爲空,則遞歸查找
if(root.left != null){
findPath(root.left, eS, path, cS);
}
//若右子樹不爲空,則遞歸查找
if(root.right != null){
findPath(root.right, eS, path, cS);
}
//在返回父結點之前,在路徑上刪除當前結點
path.pop();
}
}
class TreeNode{
int data;
TreeNode left;
TreeNode right;
public TreeNode(int x){
data = x;
left = null;
right = null;
}
}