zoukankan      html  css  js  c++  java
  • 113 Path Sum II 路径总和 II

    给定一个二叉树和一个和,找到所有从根到叶路径总和等于给定总和的路径。
    例如,
    给定下面的二叉树和 sum = 22,
                  5
                 /
                4   8
               /   /
              11  13  4
             /      /
            7    2  5   1
    返回
    [
       [5,4,11,2],
       [5,8,4,5]
    ]

    详见:https://leetcode.com/problems/path-sum-ii/description/

    Java实现:

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        public List<List<Integer>> pathSum(TreeNode root, int sum) {
            List<List<Integer>> res=new ArrayList<List<Integer>>();
            if(root==null){
                return res;
            }
            helper(root,sum,new ArrayList<Integer>(),res);
            return res;
        }
        private void helper(TreeNode root,int sum,ArrayList<Integer> path,List<List<Integer>> res){
            if(root==null){
                return;
            }
            path.add(root.val);
            if(root.val==sum&&root.left==null&&root.right==null){
                res.add(new ArrayList<Integer>(path));
            }else{
                helper(root.left,sum-root.val,path,res);
                helper(root.right,sum-root.val,path,res);
            }
            path.remove(path.size()-1);
        }
    }
    

     python实现:

  • 相关阅读:
    PHP 7安装使用体验,升级PHP要谨慎
    PHP里10个鲜为人知但却非常有用的函数
    解决 PHPExcel 长数字串显示为科学计数
    linux安装jdk1.6
    虚拟机下Redhat9 网络配置问题(转)
    windows下的一些命令
    redis高级应用特征
    乐观锁的概念
    windows配置redis(转)
    redis常用命令
  • 原文地址:https://www.cnblogs.com/xidian2014/p/8719583.html
Copyright © 2011-2022 走看看