• 二叉树中和为某一值的路径 --剑指offer


    输入一颗二叉树的根节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。(注意: 在返回值的list中,数组长度大的数组靠前)

    用树的先序遍历来记录路径

    public class Solution {
        ArrayList<ArrayList<Integer>> paths=new ArrayList<ArrayList<Integer>>();
        ArrayList<Integer> path=new ArrayList<Integer>();//存储当前的路径
        public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {
            if(target < 0){
                return  paths;
            }
            if(root == null){
                return paths;
            }
            path.add(root.val);
            if(root.left == null &&root.right==null&& target == root.val){
                paths.add(new ArrayList<Integer>(path));
            }
            if(root.val < target && root.left!=null){
                FindPath(root.left,target-root.val);
            }
            if(root.val < target&& root.left!=null){
                FindPath(root.right,target-root.val);
            }
    //遍历完一条路径之后需要回溯 path.remove(path.size()
    -1); return paths; } }

    参考博客:https://blog.csdn.net/u014525494/article/details/80978647

    只完全弄懂了一部分 记录等之后在来看

  • 相关阅读:
    线程3 线程池和文件下载服务器
    线程 2
    线程 1
    线程间操作
    编写高质量的代码-------从命名开始
    基于.NET平台常用的框架整理
    消息队列
    我是一个线程
    linux 网络命令
    css hack比较全 --- 转
  • 原文地址:https://www.cnblogs.com/nlw-blog/p/12430389.html
Copyright © 2020-2023  润新知