题目:输入一颗二叉树和一个整数,打印出二叉树中节点值得和为输入整数的所有路径
分析:递归
public class FindPath {
public static void findPath(Node root,int target,ArrayList
toPrint,int now){
if(root==null)
return;
now = now+root.getData();
toPrint.add(root.getData());
if(now==target && root.getLeft()==null && root.getRight()==null){
System.out.println(toPrint);
toPrint.remove(toPrint.size()-1);
return;
}else{
if(root.getLeft()!=null){
findPath(root.getLeft(), target, toPrint, now);
}
if(root.getRight()!=null){
findPath(root.getRight(), target, toPrint, now);
}
toPrint.remove(toPrint.size()-1);
}
}
}
class Node{
private int data;
private Node left;
private Node right;
public Node(int data) {
super();
this.data = data;
}
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
public Node getLeft() {
return left;
}
public void setLeft(Node left) {
this.left = left;
}
public Node getRight() {
return right;
}
public void setRight(Node right) {
this.right = right;
}
@Override
public String toString() {
return "Node [data=" + data + "]";
}
public Node() {
super();
}
}