zoukankan      html  css  js  c++  java
  • LeetCode 113 路经总和II

    LeetCode 113 路经总和II

    问题描述:
    给定一个二叉树和一个目标和,找到所有从根节点到叶子节点路径总和等于给定目标和的路径。

    DFS+回溯

    执行用时:1 ms, 在所有 Java 提交中击败了100.00%的用户
    内存消耗:39.6 MB, 在所有 Java 提交中击败了10.71%的用户

    class Solution {
        public List<List<Integer>> pathSum(TreeNode root, int sum) {
            //根节点到叶子节点路径和为给定值的路径总数
            List<List<Integer>> results = new ArrayList<>();
            backtrace(root, 0, sum, new ArrayList<Integer>(), results);
    
            return results;
        }
    
        public void backtrace(TreeNode root, int currSum, int target, List<Integer> currPath, List<List<Integer>> paths) {
            if(root==null) {
                return;
            }
            //满足条件的根节点处终止并添加到结果集合
            else if(root.left==null && root.right==null && currSum==target-root.val) {
                currPath.add(root.val);
                paths.add(new ArrayList<Integer>(currPath));
                currPath.remove(currPath.size()-1);
                return;
            }
            
            //继续向下深度遍历
            currPath.add(root.val);
            currSum += root.val;
            backtrace(root.left, currSum, target, currPath, paths);
            backtrace(root.right, currSum, target, currPath, paths);
            //回溯
            currPath.remove(currPath.size()-1);
    
            return;
        }
    }
    
  • 相关阅读:
    STL-- vector中resize()和reserve()区别
    计算机网络--网络层
    计算机网络--数据链路层
    算法--排序算法
    数据结构--树--哈夫曼树
    数据结构--树--AVL树
    数据结构--树--二叉查找树
    数据结构--树--红黑树
    深入理解计算机系统读书笔记
    C++面试笔记--字符串
  • 原文地址:https://www.cnblogs.com/CodeSPA/p/13736899.html
Copyright © 2011-2022 走看看