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 }
  • 相关阅读:
    webpack打包注意事项
    打印内存, 打印16进制
    c++ 字符集转换
    RegSvr32 加载失败,找不到指定的模块
    错误码设计
    mfc 移动绘制的图形
    获取、设置光标
    c++ 函数中定义函数
    python linux 自动补全 tab.py
    3.4.5节 完整神经网络样例程序
  • 原文地址:https://www.cnblogs.com/lz87/p/7623033.html
Copyright © 2011-2022 走看看