zoukankan      html  css  js  c++  java
  • [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 }
  • 相关阅读:
    软件设计模式之简单工厂模式
    CentOS中端口操作命令
    webapi core封装树操作出现错误
    asp.net mvc中调度器(Quartz)的使用
    软件设计模式之单例模式
    layer关闭弹窗(多种关闭弹窗方法)
    Hadoop大作业
    hive基本操作与应用
    用Python编写WordCount程序任务
    熟悉HBase基本操作
  • 原文地址:https://www.cnblogs.com/lz87/p/7623033.html
Copyright © 2011-2022 走看看