• 二叉树中和为某一值的路径


    package 剑指offer.二叉树中和为某一值的路径;
    
    import java.util.ArrayList;
    
    /**
     * Created by nick on 2018/10/12.
     */
    public class Solution {
        public static void main(String[] args) {
            TreeNode root =new TreeNode(10);
            root.left=new TreeNode(5);
            root.right=new TreeNode(12);
            root.left.left=new TreeNode(4);
            root.left.right=new TreeNode(7);
            ArrayList<ArrayList<Integer>> m= new Solution().FindPath(root,22);
            System.out.println(m);
        }
        ArrayList<ArrayList<Integer>> listall = new ArrayList<ArrayList<Integer>>();
        public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {
            ArrayList<Integer> m=new ArrayList<Integer>();
            if (root == null) {
                return listall;
            }
            Find(root , target ,m);
            return listall;
        }
        public void Find(TreeNode root,int target,ArrayList<Integer> m){
    
            target=target-root.val;
            m.add(root.val);
            if(target<0||root==null)
                return;
            if(target==0&&root.right==null&&root.left==null)
            {
                ArrayList<Integer> path = new ArrayList<Integer>();
                for (int i = 0; i < m.size(); i++) {
                    path.add(m.get(i));//防止m的变化对结果的影响
                }
                listall.add(path);//list是单独的一条
                m.remove(m.size()-1);
                return;
            }
    
            if(target>0&&root.left!=null)
            {
                Find(root.left,target,m);
            }
    //      m.remove(m.size()-1);//return出来才删除
            if(target>0&&root.right!=null)
            {
                Find(root.right,target,m);
            }
            //如果当前路径值和大于目标值或者找到一条路径则回到上一层
            m.remove(m.size()-1);
        }
    }
    class TreeNode {
        int val = 0;
        TreeNode left = null;
        TreeNode right = null;
    
        public TreeNode(int val) {
            this.val = val;
    
        }
    
    }
  • 相关阅读:
    Shader_ShaderForge_NGUI_流光&波纹&消融
    “PurMVC”在Unity中的应用
    springboot整合jdbc
    ajax属性详解
    FreeMarker 日期转换失败
    freemarker404解决方案(全面)
    @RequestParam,@PathParam,@PathVariable等注解区别
    @RestController和@Controller区别
    通过code去获取他的枚举
    Servlet(三)ServletContext
  • 原文地址:https://www.cnblogs.com/nickup/p/9781205.html
Copyright © 2020-2023  润新知