zoukankan      html  css  js  c++  java
  • 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);
            
        }
    }
  • 相关阅读:
    ssh -vT git@github.com get “ No such file or directory” 错误
    提高Bash使用效率的方法
    mybatis的update使用选择
    Ping 的TTL理解
    为什么要使用oath协议?
    Rest Client插件简单介绍
    idea中查看java类继承图
    CSS单行文本溢出显示省略号
    js里父页面与子页面的相互调用
    css font的简写规则
  • 原文地址:https://www.cnblogs.com/jasminemzy/p/7842556.html
Copyright © 2011-2022 走看看