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);
        }
  • 相关阅读:
    unittest learning
    C++类和对象
    Linux shell基础(十二)
    Linux shell基础(十一)
    Linux shell基础(十)
    Linux shell基础(九)
    Linux shell基础(八)
    Linux shell基础(六)
    Linux shell基础(七)
    Linux shell基础(五)
  • 原文地址:https://www.cnblogs.com/aboutblank/p/4423296.html
Copyright © 2011-2022 走看看