题目:输入一个整数和一棵二元树。
从树的根结点开始往下访问一直到叶结点所经过的所有结点形成一条路径。
打印出和与输入整数相等的所有路径。
例如 输入整数22和如下二元树
10
/ \
5 12
/ \
4 7
则打印出两条路径:10, 12和10, 5, 7。
算法很简单,只是需要用java构造一个tree
从树的根结点开始往下访问一直到叶结点所经过的所有结点形成一条路径。
打印出和与输入整数相等的所有路径。
例如 输入整数22和如下二元树
10
/ \
5 12
/ \
4 7
则打印出两条路径:10, 12和10, 5, 7。
算法很简单,只是需要用java构造一个tree
package test;
import java.util.ArrayList;
import java.util.List;
public class FindTreePath {
public void printPath(int match,List<Integer> path,int sum,MyTree tree){
List<Integer> currentPath=new ArrayList<Integer>();
currentPath.addAll(path);
currentPath.add(tree.getCurrentNode().getValue());
sum+=tree.getCurrentNode().getValue();
if(tree.isLeaf()){
if(sum==match)System.out.println(currentPath);//找到结果并打印
}else {
if(sum<=match){//当和小于等于match时继续找
if(tree.toLeftChild())printPath(match, currentPath, sum, tree);
if(tree.toRightChild())printPath(match, currentPath, sum, tree);
}
}
tree.toParent();
}
public static void main(String[] args) {
MyTree tree=new MyTree(10);
tree.addLeftChild(5);
tree.addRightChild(12);
tree.toLeftChild();
tree.addLeftChild(4);
tree.addRightChild(7);
tree.toRoot();
FindTreePath test=new FindTreePath();
test.printPath(22, new ArrayList<Integer>(), 0, tree);
}
}
package test;
/**
* @author Administrator
*
*/
public class MyTree {
private Node currentNode;
public MyTree(int val) {
Node node = new Node();
node.setValue(val);
currentNode = node;
}
public void addLeftChild(int val) {
Node node = new Node();
node.setValue(val);
node.setParent(currentNode);
currentNode.setLeftChild(node);
}
public void addRightChild(int val) {
Node node = new Node();
node.setValue(val);
node.setParent(currentNode);
currentNode.setRightChild(node);
}
public void toRoot() {
if (currentNode.getParent() != null) {
currentNode = currentNode.getParent();
toRoot();
}
}
public boolean toParent() {
if (currentNode.getParent() != null) {
currentNode = currentNode.getParent();
return true;
}
return false;
}
public boolean toRightChild() {
if (currentNode.getRightChild() != null) {
currentNode = currentNode.getRightChild();
return true;
}
return false;
}
public boolean isLeaf(){
return currentNode.getLeftChild()==null&¤tNode.getRightChild()==null;
}
public boolean toLeftChild() {
if (currentNode.getLeftChild() != null) {
currentNode = currentNode.getLeftChild();
return true;
}
return false;
}
public Node getCurrentNode() {
return currentNode;
}
}
package test;
public class Node {
private int value;
private Node parent;
private Node leftChild;
private Node rightChild;
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public Node getParent() {
return parent;
}
public void setParent(Node parent) {
this.parent = parent;
}
public Node getLeftChild() {
return leftChild;
}
public void setLeftChild(Node leftChild) {
this.leftChild = leftChild;
}
public Node getRightChild() {
return rightChild;
}
public void setRightChild(Node rightChild) {
this.rightChild = rightChild;
}
}