zoukankan      html  css  js  c++  java
  • 二叉树中和为某一值的路径

    题目描述:

    输入一颗二叉树的根节点和一个整数,按字典序打印出二叉树中结点值的和为输入整数的所有路径。
    路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。

    题目解析:

    1.首先前序遍历,将访问的结点加入到路径中 并累加该路径结点的值;
    2.如果该结点是叶子结点 且路径上的累加值等于输入的数字,则当前路径符合要求,直接返回路径;
    3.如果该结点不是叶子结点,继续递归访问它的左右子节点;
    注意:当前结点为叶子节点 但是路径不符合要求,要从路径中删除该节点,并从累加值中减去该结点的值
    确保返回返回父节点时得到的路径刚好是从根节点到父节点的路径。



    如果题目中要求在返回值的list中,数组长度大的数组靠前,就将最后生成的list中的各个数组按照数组的长度由大到小排序,
    因为在递归方法中list中数组的添加顺序并不能保证一定是长度最长的先添加进list。

    题目解答:

    import java.util.*;
    /**
    public class TreeNode {
        int val = 0;
        TreeNode left = null;
        TreeNode right = null;
    
        public TreeNode(int val) {
            this.val = val;
        }
    }
    */
    public class Solution {
        public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {
            ArrayList<ArrayList<Integer>> res=new ArrayList<>();//返回的路径数组
            ArrayList<Integer> cur=new ArrayList<>();
     
            helper(root,target,cur,res);//cur为当前的路径
            
            Collections.sort(res, new Comparator<ArrayList<Integer>>() {
                @Override
                public int compare(ArrayList<Integer> o1, ArrayList<Integer> o2) {
                    if (o1.size()<o2.size()){
                        return 1;
                    }else return -1;
                }
            });
            return res;
        }
        
        public void helper(TreeNode root,int target,ArrayList<Integer> cur,ArrayList<ArrayList<Integer>> res){
            if (root==null) return;
            int value=root.val;
            cur.add(value);
            if (target==value && root.left==null && root.right==null){//目标值为当前值,且这个节点是叶子节点
                res.add(new ArrayList<>(cur));
            }else {
                helper(root.left,target-value,cur,res);//递归循环左右子树
                helper(root.right,target-value,cur,res);
            }
            cur.remove(cur.size()-1);//消除掉当前节点对查找路径的影响 --> 至关重要
        }
    }
    
  • 相关阅读:
    1.Mybatis的全局配置mybatis-config.xml
    01淘淘商城项目:项目Maven工程搭建
    Connection timed out: connect; Communications link failure
    启动maven项目的配置
    PLSQL 触发器概念
    Git 概念&常用命令
    Git与svn的区别 & Git的工作流程
    Redis 是如何存储的
    Redis 概念,常用命令
    idea 快捷键
  • 原文地址:https://www.cnblogs.com/yzhengy/p/13236263.html
Copyright © 2011-2022 走看看