【剑指offer】二叉树中和为某一值的路径

来源:互联网 发布:pc版mac系统下载 编辑:程序博客网 时间:2024/05/20 06:27

题目:

输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。


分析:

深度优先遍历,将节点的值加入路径中,没有达到预定值,继续深入,超出预定值后退到上一节点。需要注意有可能有多条路径符合条件,要将多条路径都返回。


实现:

public ArrayList<ArrayList<Integer>> FindPath(TreeNode root, int target) {ArrayList<ArrayList<Integer>> lists = new ArrayList<ArrayList<Integer>>();if (root == null) {return lists;}ArrayList<Integer> route = new ArrayList<Integer>();find(root, target, lists, route, 0);return lists;}public void find(TreeNode node, int target,ArrayList<ArrayList<Integer>> lists, ArrayList<Integer> route,int current) {current += node.val;route.add(node.val);boolean leaf = (node.left == null) && (node.right == null);if (current == target && leaf) {lists.add(new ArrayList<Integer>(route));} else if (current < target) {if (node.left != null) {find(node.left, target, lists, route, current);}if (node.right != null) {find(node.right, target, lists, route, current);}}route.remove(route.size() - 1);}


0 0
原创粉丝点击