1、二叉树和为Sum的路径
1.1 递归实现
public static void findPath(Node root, int aim, Stack<Integer> stack, int currentSum) {
currentSum += root.val;
stack.push(root.val);
if (root.left == null && root.right == null) {
if (currentSum == aim) {
for (int path : stack) {
System.out.print(path + " ");
}
System.out.println();
}
}
if (root.left != null) {
findPath(root.left, aim, stack, currentSum);
}
if (root.right != null) {
findPath(root.right, aim, stack, currentSum);
}
stack.pop();
}
1.2 递归实现
打印所有和为aim的路径
public static void iterator(Node root,String s,int t,int aim) {
if(root==null){
return;
}
s+=root.dat+" ";
t+=root.dat;
if(root.left==null&&root.right==null) {
if(t==aim){
System.out.println(
s.trim().replaceAll(" ","->"));
}
}
iterator(root.left,s,t,aim);
iterator(root.right,s,t,aim);
}
注:以上搜索路径时:
1
2 3
4
输出:1 2 4
1 3
不会输出:1 2
1.3 二叉树的非递归先序遍历实现
public void findPath(Node root,int sum){
if(root==null){
return;
}
Stack<Node> stack=new Stack<Node>();
Node head=root;
stack.push(head);
int cur=0;
List<Integer> list=new ArrayList<Integer>();
while(!stack.isEmpty()){
head=stack.peek();
cur+=head.dat;
list.add(head.dat);
if(head.right!=null){
stack.push(head.right);
}
if(head.left!=null){
stack.push(head.left);
}
if(head.left==null&&head.right==null){
if(cur==sum){
System.out.println(cur);
break;
}else if(!stack.isEmpty()){
Node tmp=stack.pop();
cur-=tmp.dat;
list.remove(list.size()-1);
}
}
}
System.out.println(list);
}
2、所有路径
- 所有路径
public static List<List<Integer>> pathSum1(Node root,int sum,List<List<Integer>> listAll,List<Integer> list){
if(root == null)
return listAll;
list.add(root.dat);
if(root.left==null||root.right==null){
listAll.add(new ArrayList<Integer>(list));
}
pathSum1(root.left, sum,listAll,list);
pathSum1(root.right, sum,listAll,list);
list.remove(list.size()-1);
return listAll;
}
- 和为Sum路径
public static List<List<Integer>> pathSum(Node root,int sum,List<List<Integer>> listAll,List<Integer> list){
if(root == null)
return listAll;
list.add(root.dat);
sum-=root.dat;
if((root.left == null||root.right == null)
&&sum == 0){
listAll.add(new ArrayList<Integer>(list));
}
pathSum(root.left, sum,listAll,list);
pathSum(root.right, sum,listAll,list);
list.remove(list.size()-1);
return listAll;
}