二叉树中和为某一值的路径
题目
输入一棵二叉树和整数,打印出二叉树中节点值得和为输入整数的所有路径。从树的根节点开始往下一直到叶节点所经过的节点形成一条路径。
二叉树的定义如下:
public class BinaryTreeNode{
int value;
BinaryTreeNode left;
BinaryTreeNode right;
}
思路
我们使用前序遍历的方式访问某一结点,我们就把该结点加入到栈中。并累加该结点的值。如果该结点为叶节点,并且路径中结点值的和刚好等于输入的整数,则当前路径符合要求,并打印出来。如果当前节点不是叶节点,则继续访问它的子节点。当节点访问结束后,递归函数将自动回到它的父节点。我们不难看出,保存路径的数据结构实际上是一个栈。
代码
public void FindPath(BinaryTreeNode root, int sum ){
if(root == null )
return;
Stack<Integer> path = new Stack<Integer>();
FindPath(root, sum, path);
}
public void FindPath(BinaryTreeNode root, int sum, Stack<Integer> path){
if(root==null)
return;
//如果是叶节点,并且路径上节点的值的和等于输入的值
//则打印出这条路径
if(root.leftNode == null && root.rightNode == null){
if(root.value == sum){
System.out.println("路径开始");
for(int i :path)
System.out.print(i+",");
System.out.print(root.value);
}
}
else{
path.push(root.value);
findPath(root.left,sum-root.value,path);
findPath(root.right,sum-root.value,path);
path.pop();
}
}