• leetcode113- Path Sum II- medium


    Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.

    For example:
    Given the below binary tree and sum = 22,

                  5
                 / 
                4   8
               /   / 
              11  13  4
             /      / 
            7    2  5   1
    

    return

    [
       [5,4,11,2],
       [5,8,4,5]
    ]

    DFS。这题叶子节点和null分开处理。要小心叶子节点那里允许加个别点的时候,加完result也要remove!所有crt buffer里面的add 和 remove操作必须同时搭配!!

    /**
     * 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>> result = new ArrayList<>();
            List<Integer> crt = new ArrayList<>();
            dfs(root, sum, crt, result);
            return result;
        }
        
        private void dfs(TreeNode root, int dist, List<Integer> crt, List<List<Integer>> result) {
            
            if (root == null) {
                return;
            }
            
            if (root.left == null && root.right == null && root.val == dist) {
                crt.add(root.val);
                result.add(new ArrayList<Integer>(crt));
                // 千万小心这里也得remove!!
                crt.remove(crt.size() - 1);
                return;
            }
            
            crt.add(root.val);
            dfs(root.left, dist - root.val, crt, result);
            dfs(root.right, dist - root.val, crt, result);
            crt.remove(crt.size() - 1);
            
        }
    }
  • 相关阅读:
    postman调试参数格式
    Dapper.Contrib.Extensions扩展
    kafka dashborad 安装流程(kafka_exporter + prometheus + grafana)
    Kafka学习入门(windows环境下)
    Windows环境下载安装Kafka
    Windows环境下Zookeeper的安装及启动
    hdu4087(概率dp)
    poj3162(树形dp+线段树)
    Gym
    牛客小白月赛13 小A的柱状图(单调栈)
  • 原文地址:https://www.cnblogs.com/jasminemzy/p/7842556.html
Copyright © 2020-2023  润新知