/****************************************************************************************
*题目:二叉树中和为某一值的路径
* 输入一颗二叉树和一个整数,打印出二叉树中节点值和尾输入整数的所有路径。从树的根节点开始往下一直到
* 叶节点所经过的结点形成一条路径。
*时间:2015年9月5日10:53:32
*文件:PathInTree.java
*作者:cutter_point
****************************************************************************************/
package bishi.Offer50.y2015.m09.d05;
import java.util.*;
import bishi.Offer50.y2015.m08.d26.*;
public class PathInTree
{
public void findPath(BinaryTreeNode pRoot, int expectedSum)
{
if(pRoot == null)
return;
Vector<BinaryTreeNode> path = new Vector<BinaryTreeNode>();
int currentSum = 0;
findPath(pRoot, expectedSum, path, currentSum);
}
/**
* 用来寻找我们的路径,我们用递归,这样就可以自动返回到前一个根节点了
* @param pRoot 当前遍历到的节点
* @param expectedSum 我们统计的目标
* @param path 记录我们的路径
* @param currentSum 当前的和
*/
private void findPath(BinaryTreeNode pRoot, int expectedSum, Vector<BinaryTreeNode> path, int currentSum)
{
currentSum += pRoot.m_nValue;
path.add(pRoot);
boolean isLeaf = pRoot.m_pLeft == null && pRoot.m_pRight == null;
if(isLeaf && currentSum == expectedSum)
{
System.out.println("路径已经找到:");
for(int i = 0; i < path.size(); ++i)
{
System.out.print(path.get(i).m_nValue + "\t");
}
System.out.println();
}
if(pRoot.m_pLeft != null)
{
findPath(pRoot.m_pLeft, expectedSum, path, currentSum);
}
if(pRoot.m_pRight != null)
{
findPath(pRoot.m_pRight, expectedSum, path, currentSum);
}
currentSum -= pRoot.m_nValue;
path.remove(pRoot);
}
public static void main(String[] args)
{
int preorder[] = {1,2,4,7,3,5,6,8};
int inorder[] = {4,7,2,1,5,3,8,6};
BinaryTree bt = new BinaryTree();
bt.construct(preorder, inorder);
PathInTree pit = new PathInTree();
pit.findPath(bt.root, 9);
}
}