• 输出二叉树所有路径,java


    package main.java;/*
    * @Description: 遍历所有的树
    * @Author: du_zj
    * @Date: 2022/3/22.
    */

    import java.util.ArrayList;
    import java.util.List;

    public class ListTree {


    public boolean hasPathSum(TreeNode root, int sum) {
    List<Integer> list = new ArrayList<>();
    dfs(root, list);
    List<String> strings = new ArrayList<>();
    helper(root, root.val + "", strings);
    System.out.println(strings);
    return true;
    }

    public void helper(TreeNode root, String path, List<String> result) {
    if (root == null) {
    return;
    }

    if (root.left == null && root.right == null) {
    result.add(path);
    return;
    }

    if (root.left != null) {
    helper(root.left, path + "->" + root.left.val, result);
    }

    if (root.right != null) {
    helper(root.right, path + "->" + root.right.val, result);
    }
    }



    List<List<Integer>> results = new ArrayList<>();
    public boolean hasPathSum2(TreeNode root, int sum) {
    List<Integer> list = new ArrayList<>();
    dfs(root, list);
    System.out.println(results.toString());
    return true;
    }



    private void dfs(TreeNode root, List<Integer> list) {
    if (root == null) {
    return;
    }
    if (root.left == null && root.right == null) {
    results.add(list);
    }
    list.add(root.val);
    if (root.left != null) {
    dfs(root.left, new ArrayList<>(list));
    }
    if (root.right != null) {
    dfs(root.right, new ArrayList<>(list));
    }
    }

    static class TreeNode{
    TreeNode left;
    TreeNode right;
    Integer val;

    }
    public static void main(String[] args) {
    TreeNode root1 = new TreeNode();
    TreeNode root2 = new TreeNode();
    TreeNode root3 = new TreeNode();
    TreeNode root4 = new TreeNode();
    TreeNode root5 = new TreeNode();
    root1.val = 10;
    root2.left = root1;
    root3.val = 8;
    root2.right = root3;
    root2.val = 6;
    root4.left = root2;
    root4.val = 2;
    root5.val = 0;
    root4.right = root5;
    int sum = 0;
    ListTree nv = new ListTree();
    nv.hasPathSum(root4,sum);
    }
    }
  • 相关阅读:
    竞赛200
    竞赛202
    判断是node还是 浏览器端 typeof xxx==='string'
    闷油瓶
    关于算法题
    堆 heap, 准备博客参考
    私有npm 上发布 包
    竞赛199
    正则,转换数组
    设计模式之模板设计模式-以spring的各种template为例
  • 原文地址:https://www.cnblogs.com/duzjextjs/p/16038032.html
Copyright © 2020-2023  润新知