求葉子節點到根結點路徑和爲14,並且打印路徑

求葉子節點到根結點路徑和爲14,並且打印路徑,實現過程如下所示:

package cn.edu.nwu.structs.tree;

/**
 * @author jcm
 * 求根節點到葉子節點路徑和爲14,這是百度面試題
 * 時間 2016年9月1日
 */
public class PrintTreeNodePath {
	//定義棧
	public static BinaryTreeNode[] stack = new BinaryTreeNode[50];
	public static int top = 0;//棧指針
	public static void main(String[] args) {
		BinaryTreeNode root = createBinaryTree();
		show(root,1);
		printPath(root,14,0);
	}
	/**
	 * @author jcm
	 * 求葉子節點到根結點路徑和爲14,並打印路徑
	 * @param root 樹根節點
	 * @param sum 樹根到葉子節點的路徑和爲14(是題目給定的要求路徑和)
	 * @param currentSum 當前路徑和
	 */
	public static void printPath(BinaryTreeNode root,int sum,int currentSum){
		if(root == null){
			return ;
		}
		currentSum += root.data;//進棧的前要計算根節點到當前結點的計算和
		stack[top++] = root;
		//滿足葉子節點和當前路徑和等於題目給定的14.
		if(root.leftTreeNode == null && root.rightTreeNode == null && currentSum == sum){
			for(int i=0;i<top;i++){
				System.out.print(stack[i].data+" ");
			}
			System.out.println();
		}else{
			printPath(root.leftTreeNode,sum,currentSum);//左子樹遞歸,右子樹遞歸
			printPath(root.rightTreeNode,sum,currentSum);
		}
		currentSum -=root.data;//所有遍歷完之後要出棧
		top--;
	}
	/**
	 * @author jcm
	 *  構建二叉樹
	 * @return
	 */
	public static BinaryTreeNode createBinaryTree() {
		BinaryTreeNode root = null;
		BinaryTreeNode tree1 = new BinaryTreeNode(3);
		BinaryTreeNode tree2 = new BinaryTreeNode(6);
		BinaryTreeNode tree3 = new BinaryTreeNode(4);
		BinaryTreeNode tree4 = new BinaryTreeNode(5);
		BinaryTreeNode tree5 = new BinaryTreeNode(7);
		BinaryTreeNode tree6 = new BinaryTreeNode(2);
		BinaryTreeNode tree7 = new BinaryTreeNode(4);
		root = tree1;//根結點指向第1棵樹
		tree1.leftTreeNode = tree2;
		tree1.rightTreeNode = tree5;
		tree2.leftTreeNode = tree3;
		tree2.rightTreeNode = tree4;
		tree5.leftTreeNode = tree6;
		tree5.rightTreeNode = tree7;
		return root;
	}
	//中序遍歷,通過n控制層數
	public static void show(BinaryTreeNode root,int n){
		if(root == null){
			return ;
		}else{
			show(root.leftTreeNode,n+1);
			for (int i=0;i<n;i++){
				System.out.print("	");
			}
			System.out.println(root.data);
			show(root.rightTreeNode,n+1);
		}
	}
}

輸出路徑是:3 6 5

                        3 7 4

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章