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

  • 相关阅读:
    单件模式 Singleton---Design Pattern 5
    Web请求中同步与异步的区别
    zepto和jquery的区别,zepto的不同使用8条小结
    zepto判断左右滑动
    移动web终端交互优化
    Flexbox
    设计移动web
    viewport
    Pixel移动开发像素知识
    获取元素的left值
  • 原文地址:https://www.cnblogs.com/xidian2014/p/8719583.html
Copyright © 2011-2022 走看看