zoukankan      html  css  js  c++  java
  • Path Sum II——LeetCode

    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,首先把当前节点入栈,然后分别递归左右子树,如果当前节点为空直接退出,如果当前节点是叶结点但是到根节点的路径和不等于指定的数也直接退出,如果等于指定的数,那么把这条路径加入结果List,递归完之后回退到上一层。

        public List<List<Integer>> pathSum(TreeNode root, int sum) {
            List<List<Integer>> res = new ArrayList<>();
            if (root == null) {
                return res;
            }
            List<Integer> tmp = new ArrayList<>();
            path(root, tmp, res, sum);
            return res;
        }
    
        public void path(TreeNode node, List<Integer> tmp, List<List<Integer>> res, int sum) {
            if (node == null) {
                return;
            }
            if (sum != node.val && node.left == null && node.right == null) {
                return;
            }
            tmp.add(node.val);
            if (sum == node.val && node.left == null && node.right == null) {
                res.add(new ArrayList<>(tmp));
                tmp.remove(tmp.size() - 1);
                return;
            }
            path(node.left, tmp, res, sum - node.val);
            path(node.right, tmp, res, sum - node.val);
            tmp.remove(tmp.size() - 1);
        }
  • 相关阅读:
    在ireport中使用checkbox
    OpenCV-Python教程(9、使用霍夫变换检测直线)
    编程挑战(6)
    [置顶] Guava学习之Immutable集合
    mongodb在PHP下的应用学习笔记
    通过Camera进行拍照
    无法删除 C_PAN.GHO: 访问被拒绝 解决办法
    使用POI生成Excel报表
    debian下使用siege进行压力测试
    jodd-servlet工具集锦
  • 原文地址:https://www.cnblogs.com/aboutblank/p/4423296.html
Copyright © 2011-2022 走看看