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

    package Leetcode;
    import java.util.*;
    //输入一棵二叉树和一个整数,打印出二叉树中节点值的和为输入整数的所有路径。从树的根节点开始往下一直到叶节点所经过的节点形成一条路径。
    //回溯
    public class test34 {
        public static void main(String[] args) {
            TreeNode root=new TreeNode(5);
            root.left=new TreeNode(4);
            root.right=new TreeNode(8);
            root.left.left=new TreeNode(11);
            root.right.left=new TreeNode(13);
            root.right.right=new TreeNode(4);
            root.left.left.left=new TreeNode(7);
            root.left.left.right=new TreeNode(2);
            root.right.right.left=new TreeNode(5);
            root.right.right.right=new TreeNode(1);
            int sum=22;
            List<List<Integer>> list=pathSum(root, sum);    
            int x=0;
        }
        public static List<List<Integer>> pathSum(TreeNode root, int sum) {
            if(root==null){
                return new ArrayList<>();
            }
            List<List<Integer>> result=new ArrayList();
            helper(root,sum,new ArrayList<>(),result);
            return result;
        }
        public static void helper(TreeNode root, int sum,List<Integer> temp,List<List<Integer>> list) {
            if(root==null){
                return;
            }
            temp.add(root.val);
            if(root.left==null&&root.right==null){
                if(sum==root.val){
                    list.add(new ArrayList<>(temp));
                    
                }
                temp.remove(temp.size()-1);
                return;
            }
            helper(root.left, sum-root.val, temp, list);
            helper(root.right, sum-root.val, temp, list);
            temp.remove(temp.size()-1);
          
            
    
            
        }
    
    }
  • 相关阅读:
    你看,那个人好像一条狗哎
    我竟然被抓去做了比特币挖矿工
    聊聊JAVA中 String类为什么不可变
    三分钟深入TT猫之故障转移
    shell实现两个数的相加
    shell截取字符串的方法
    Vi命令:如何删除全部内容?
    bash中不可以用字符串做数组下标
    awk打印出当前行的上一行
    awk同时处理多个文件
  • 原文地址:https://www.cnblogs.com/jieyi/p/14236158.html
Copyright © 2011-2022 走看看