[GeeksForGeeks] Generate all root to leaf paths of a binary tree

Given a binary tree, generate all root to leaf paths of a binary tree.

Example:

Example Tree

Example Tree

The output for the above example is [[1, 2, 4], [1, 2, 5], [1,3]]

Key idea: root to leaf path, root node comes first, so use pre-order traversal.

 1 import java.util.ArrayList;
 2 
 3 public class RootToLeafPaths {
 4     public static ArrayList<ArrayList<Integer>> getRootToLeafPaths(TreeNode root) {
 5         ArrayList<ArrayList<Integer>> paths = new ArrayList<>();
 6         if(root == null) {
 7             return paths;
 8         }
 9         preOrder(paths, new ArrayList<Integer>(), root);
10         return paths;
11     }
12     private static void preOrder(ArrayList<ArrayList<Integer>> paths, ArrayList<Integer> path, TreeNode node) {
13         path.add(node.val);
14         if(node.left == null && node.right == null) {
15             paths.add(new ArrayList<Integer>(path));
16         }
17         else {
18             preOrder(paths, path, node.left);
19             preOrder(paths, path, node.right);            
20         }
21         path.remove(path.size() - 1);
22     }
23     public static void main(String[] args) {
24         TreeNode[] nodes = new TreeNode[5];
25         for(int i = 0; i < 5; i ++) {
26             nodes[i] = new TreeNode(i);
27         }
28         nodes[0].left = nodes[1]; nodes[0].right = nodes[2];
29         nodes[1].left = nodes[3]; nodes[1].right = nodes[4];
30         ArrayList<ArrayList<Integer>> paths = getRootToLeafPaths(nodes[0]);
31         for(int i = 0; i < paths.size(); i++) {
32             for(int j = 0; j < paths.get(i).size(); j++) {
33                 System.out.print(paths.get(i).get(j) + " ");
34             }
35             System.out.println();
36         }        
37     }
38 }
原文地址:https://www.cnblogs.com/lz87/p/7623033.html