• 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实现:

  • 相关阅读:
    kill tomcat with netstat
    windows cmd命令显示UTF8设置
    rtx没有振动功能
    手动加载rvm
    RESTful Java client with Apache HttpClient
    Set Up Git on windows also use github
    lcs.py 最长公共子串算法
    如何:对代理使用 IP 切换
    这个博客站点不错
    a case study
  • 原文地址:https://www.cnblogs.com/xidian2014/p/8719583.html
Copyright © 2020-2023  润新知