剑指Offer——树的子结构二叉树中和为某一值的路径
1、题目描述
输入一颗二叉树的跟节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。(注意: 在返回值的list中,数组长度大的数组靠前)
2、代码实现
package com.baozi.offer;
import java.util.ArrayList;
/**
* 输入一颗二叉树的跟节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。
* 路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
* (注意: 在返回值的list中,数组长度大的数组靠前)
*测试用例:
* 0
* / \
* 1 2
* / \ / \
* 3 4 5 6
* \
* 7
* @author BaoZi
* @create 2019-07-12-19:21
*/
public class Offer20 {
public static void main(String[] args) {
TreeNode root = new TreeNode(0);
TreeNode t1 = new TreeNode(1);
TreeNode t2 = new TreeNode(2);
TreeNode t3 = new TreeNode(3);
TreeNode t4 = new TreeNode(4);
TreeNode t5 = new TreeNode(5);
TreeNode t6 = new TreeNode(6);
TreeNode t7 = new TreeNode(7);
root.left = t1;
root.right = t2;
t1.left = t3;
t1.right = t4;
t2.left = t5;
t2.right = t6;
t5.right = t7;
Offer20 offer20 = new Offer20();
ArrayList<ArrayList<Integer>> arrayLists = offer20.FindPath(root, 4);
for (int i = 0; i < arrayLists.size(); i++) {
for (int j = 0; j < arrayLists.get(i).size(); j++) {
System.out.print("--->"+arrayLists.get(i).get(j) );
}
}
}
ArrayList<ArrayList<Integer>> listAll = new ArrayList<>();
ArrayList<Integer> list = new ArrayList<>();
public ArrayList<ArrayList<Integer>> FindPath(TreeNode root, int target) {
if (root == null) {
return listAll;
}
list.add(root.val);
target -= root.val;
if (target == 0 && root.left == null && root.right == null) {
//这里必须是把list重新创建一个然后添加进listAll中,因为原来的list还要进行下边的操作
listAll.add(new ArrayList<Integer>(list));
}
FindPath(root.left, target);
FindPath(root.right, target);
//这里使用的是回溯思想,当如果某一条路径走到尽头但是target的值不为0的话,需要把最后一个节点的值减去
list.remove(list.size() - 1);
return listAll;
}
}
浙公网安备 33010602011771号