package 二叉树; import java.util.*; public class 二叉树根到叶子节点的路径和 { public static TreeNode root; public static Set<List<Integer>> set = new HashSet<>(); public static List<Integer> list = new ArrayList<>(); public static List<Integer> sum = new ArrayList<>(); public static void createTree(Integer[] objects){ List<TreeNode> datas = new ArrayList<>();//存储所有节点 for(Integer obj:objects){ datas.add(new TreeNode(obj)); } root = datas.get(0);//将一个作为根节点 for(int i = 0;i < objects.length/2;i++){ datas.get(i).left = datas.get(2*i+1); if(2*i+2 < objects.length){//避免偶数的时候,下标越界 datas.get(i).right = datas.get(2*i+2); } } } public static void DFS(TreeNode T,int preVal,List<Integer> list){ if(T!=null){ preVal+=T.val; list.add(T.val); if(T.left==null&&T.right==null){ System.out.println(list); set.add(new ArrayList<>(list)); sum.add(preVal); }else{ DFS(T.left,preVal,list); DFS(T.right,preVal,list); } //当T是叶子节点,在当前递归状态下需要剔除该元素 list.remove(list.size()-1); } } public static void getPath(TreeNode root,List<Integer> list,int num){ if(root!=null) { num+=root.val; list.add(root.val); } if(root.left == null && root.right == null){ System.out.print(num+"="); System.out.println(list); sum.add(num); set.add(new ArrayList<>(list)); } if(root.left != null) getPath(root.left,list,num); if(root.right != null) getPath(root.right,list,num); list.remove(list.size()-1); } public static List<String> binaryTreePaths(TreeNode root) { List<String> list=new ArrayList<String>(); Queue<TreeNode> queue=new LinkedList<TreeNode>(); Queue<String> qStr=new LinkedList<String>(); if (root==null) return list; queue.add(root); qStr.add(""); while(!queue.isEmpty()) { TreeNode curNode=queue.remove(); String curStr=qStr.remove(); if (curNode.left==null && curNode.right==null) list.add(curStr+curNode.val); if (curNode.left!=null) { queue.add(curNode.left); qStr.add(curStr+curNode.val+"->"); } if (curNode.right!=null) { queue.add(curNode.right); qStr.add(curStr+curNode.val+"->"); } } return list; } public static void main(String[] args) { Integer[] arr = {1,3,2,4,5,2,1}; createTree(arr); DFS(root,0,list); sum.clear(); getPath(root,list,0); System.out.println(sum); System.out.println(set); System.out.println(binaryTreePaths(root)); } }