您的位置:首页 > 理论基础 > 数据结构算法

数据结构面试题1.2.5-在二元树中找出和为某一值的所有路径

2015-09-12 16:51 585 查看
package questions;

import java.util.ArrayList;

/**
* @title 在二元树中找出和为某一值的所有路径
* @question 输入一个整数和一棵二元树 从树的根结点开始向下访问一直到叶结点所经过的所有结点形成一条路径。 打印出和与输入整数相等的所有路径
*           例如输入的整数22和如下二元树<br>
*           .....10<br>
*           ...../\<br>
*           ....5 12<br>
*           .../\<br>
*           ..4 7 <br>
*           ./\ /\<br>
*           3 . . 9 <br>
*           则打印出两条路径10,12和10,5,7
* @author Sam
*
*/
public class Ex1o2o5 {

public static void main(String[] args) {
BSTreeNode tree = new BSTreeNode();
tree.add(10);
tree.add(5);
tree.add(12);
tree.add(4);
tree.add(7);
tree.add(9);
tree.add(3);

printSumPath(tree, 22);
//		printSumPath(tree, 31);
}

public static void LNR(BSTreeNode node) {
if (null == node) {
return;
}
System.out.print(String.format(" %d", node.value));
LNR(node.left);
LNR(node.right);
}

public static void RNL(BSTreeNode node) {
if (null == node) {
return;
}
System.out.print(String.format(" %d", node.value));
RNL(node.right);
RNL(node.left);
}

/**
* 输入指定的和及二元树
* @param node
* @param sumValue
*/
public static void printSumPath(BSTreeNode node, int sumValue) {
printSumPath(node, new ArrayList<Integer>(), 0, sumValue);
}

/**
*
* @param node 结点
* @param path 路径存储集合
* @param tempSum 临时路径的和
* @param sumValue 路径的和
*/
private static void printSumPath(BSTreeNode node, ArrayList<Integer> path,
int tempSum, int sumValue) {
if (null == node) {
return;
}
tempSum += node.value;
path.add(node.value);

boolean isLeaf = (null == node.left && null == node.right);//是否为叶结点
if (isLeaf && tempSum == sumValue) {//满足将路径打印出
for (int i : path) {
System.out.print(String.format(" %d", i));
}
System.out.println();
}

//先序遍历
printSumPath(node.left, path, tempSum, sumValue);
printSumPath(node.right, path, tempSum, sumValue);

//保证递归完成后返回父结点时路径是根结点到父结点的路径,之后遍历父结点的其它子结点,没有则返回到爷爷结点...
path.remove(path.size() - 1);
//补充,如果path不是指针而是基本类型的话,这句话就没用了(放在递归调用下面就没有用了),算法也废了,
//比如在这里加入一句tempSum+=XX;对结果没有任何影响,不会影响递归return时其它函数里的参数。
}

}

/**
* @see questions.Ex1o2o1.BSTreeNode
* @author Sam
*
*/
/*
* class BSTreeNode { int value;// value of node BSTreeNode left;// left child
* of node BSTreeNode right;// right child of node
*
* public void add(int intValue) { if (0 == value) { value = intValue; } else if
* (intValue < value) { if (null == left) { left = new BSTreeNode(); }
* left.add(intValue); } else if (intValue > value) { if (null == right) { right
* = new BSTreeNode(); } right.add(intValue); } } }
*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: