zoukankan      html  css  js  c++  java
  • 二叉树中和为某一值的路径 --剑指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

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

  • 相关阅读:
    C#连接db2数据库
    SSIS 查找 组件
    Winfrom控件 特效
    Highcharts中文帮助文档
    winform常用控件介绍
    Sql 语句常语法
    SQL经典语句大全
    SharePoint资料
    wcf编程资料
    CrystalDecisions.Windows.Forms文件
  • 原文地址:https://www.cnblogs.com/nlw-blog/p/12430389.html
Copyright © 2011-2022 走看看