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

Posted Push your limit!

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[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

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 }

 

以上是关于[GeeksForGeeks] Generate all root to leaf paths of a binary tree的主要内容,如果未能解决你的问题,请参考以下文章

GeeksForGeeks 翻译计划

geeksforgeeks@ Equal to product (Binary Search)

geeksforgeeks@ Maximum Index (Dynamic Programming)

c_cpp 键盘打字 - GeeksforGeeks

geeksforgeeks@ Minimum sum partition (Dynamic Programming)

[GeeksForGeeks] Perfect Binary Tree