問題描述:java
輸入一個整數和一棵二元樹。從樹的根結點開始往下訪問一直到葉結點所通過的全部結點造成一條路徑。打印出和與輸入整數相等的全部路徑。數據結構
例如輸入整數30和以下二元樹spa
14code
/ \遞歸
5 16io
/ \class
3 11import
則打印出兩條路徑:14, 16 和14, 5, 11。date
二元樹節點的數據結構定義爲:file
class BSTreeNode{ BSTreeNode(int x, BSTreeNode lt, BSTreeNode rt){ value = x; left = lt; right = rt; } int value; BSTreeNode left; BSTreeNode right; }
在遍歷樹的過程當中,使用stack保存所走過的路徑。若是當前節點爲葉子節點,而且路徑和等於輸入的整數,則輸出路徑。若是當前節點不是葉子節點,則遞歸的訪問它的孩子節點。在回溯的過程當中,注意路徑的出棧。
代碼實現:
package oschina.mianshi; /** * @project: oschina * @filename: IT3.java * @version: 0.10 * @author: JM Han * @date: 14:59 2015/10/22 * @comment: Test Purpose * @result: */ import java.util.Stack; import static tool.util.*; class BSTree3{ class BSTreeNode{ BSTreeNode(int x, BSTreeNode lt, BSTreeNode rt){ value = x; left = lt; right = rt; } int value; BSTreeNode left; BSTreeNode right; } private BSTreeNode root; private int currentSum; private Stack<Integer> path; public BSTree3(){ root = null; currentSum = 0; path = new Stack<Integer>(); } public void insert(int value){ root = insert(root, value); } private BSTreeNode insert(BSTreeNode t, int x){ if(null == t) return new BSTreeNode(x, null, null); if(t.value > x) t.left = insert(t.left, x); else if(t.value < x) t.right = insert(t.right, x); else ;//duplicate return t; } public void findPath(int expectSum){ findPath(root, expectSum); } private void findPath(BSTreeNode t, int expectSum){ if(null == t) return; currentSum += t.value; path.push(t.value); boolean isLeaf = (t.left == null && t.right == null); if(isLeaf && currentSum == expectSum){ printGenericColection(path); } if(null != t.left) findPath(t.left, expectSum); if(null != t.right) findPath(t.right, expectSum); currentSum -= t.value; path.pop(); } } public class IT3 { public static void main(String[] args) { BSTree3 bsTree = new BSTree3(); bsTree.insert(14); bsTree.insert(5); bsTree.insert(16); bsTree.insert(3); bsTree.insert(11); bsTree.findPath(30); } }
代碼輸出:
14 5 11 14 16