Fork me on GitHub

二叉树中和为某一值的路径

题目描述

输入一颗二叉树的跟节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。(注意: 在返回值的list中,数组长度大的数组靠前)
 1 /**
 2  * 题目描述
 3  * 输入一颗二叉树的跟节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。
 4  * 路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
 5  * (注意: 在返回值的list中,数组长度大的数组靠前)
 6  */
 7 
 8 import java.util.ArrayList;
 9 
10 public class Main24 {
11 
12     public static void main(String[] args) {
13         // TODO Auto-generated method stub
14         TreeNode root = new Main24.TreeNode(10);
15         root.left = new TreeNode(5);
16         root.left.left = new TreeNode(4);
17         root.left.right = new TreeNode(7);
18         root.left.left.left = null;
19         root.left.right.right = null;
20         
21         root.right = new TreeNode(12);
22         root.right.left = null;
23         root.right.right = null;
24         
25         ArrayList<ArrayList<Integer>> result = Main24.FindPath(root, 19);
26         System.out.println(result);
27         
28     }
29     
30     public static class TreeNode {
31         int val = 0;
32         TreeNode left = null;
33         TreeNode right = null;
34 
35         public TreeNode(int val) {
36             this.val = val;
37         }
38     }
39     
40     public static ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {    
41         ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
42         ArrayList<Integer> array = new ArrayList<>();
43         int num = 0; 
44         find(result, array, root, target, num);
45         for(int i=result.size()-2;i>=0;i--) {
46             for(int j=0;j<=i;j++) {
47                 if(result.get(j+1).size()>result.get(j).size()) {
48                     ArrayList<Integer> temp = result.get(j);
49                     result.set(j, result.get(j+1));
50                     result.set(j+1, temp);
51                 }
52             }
53         }
54         return result;    
55     }
56     
57     public static void find(ArrayList<ArrayList<Integer>> result, ArrayList<Integer> array, TreeNode root, int target, int num) {
58         if (root == null) {
59             return;
60         }
61         boolean flag = root.left == null && root.right == null;
62         num = num + root.val;
63         array.add(root.val);
64         if (num == target && flag) {
65             ArrayList<Integer> path = new ArrayList<>();
66             for (int i=0;i<array.size();i++) {
67                 path.add(array.get(i));
68             }
69             result.add(path);
70         }
71         TreeNode temp = root;
72         root = temp.left;
73         find(result, array, root, target, num);
74         root = temp.right;
75         find(result, array, root, target, num);
76         array.remove(array.size()-1);
77     }
78 }

参考:https://blog.csdn.net/lawrencelan0416/article/details/89707117 谢谢大佬!

posted @ 2019-07-05 17:52  gentleKay  阅读(152)  评论(0编辑  收藏  举报