美文网首页
leetCode 113 Path Sum2

leetCode 113 Path Sum2

作者: 进击的码农 | 来源:发表于2019-10-10 23:16 被阅读0次
  • 关键字:树、深度优先
  • 难度:Medium
  • 题目大意:给定二叉树,找到所有root-to-leaf路径和等于给定sum的所有路径。
题目:
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.

Note: A leaf is a node with no children.

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]
]
解题思路:本题与上一题path sum思路是类似的,但是需要记录所有满足条件的路径,所以重点是怎么记录路径,本文采用两个list:res记录最终结果、temp记录遍历时的每一条路径,当找到满足条件的路径后,添加到res中,回退到上一个节点时,删除temp中的当前节点。
AC代码:
/**
 * 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>> res = new ArrayList<>();
        List<Integer> temp = new ArrayList<>();
          process(root,sum,res,temp);
        return res;

    }

    public void process(TreeNode root, int sum, List<List<Integer>>res,List<Integer>temp ) {
        if (root==null) return;
        sum -= root.val;
        temp.add(root.val);
        if(root.left==null&&root.right==null) {
            if(sum==0) {
                res.add(new ArrayList<>(temp));
                temp.remove(temp.size()-1);  // 返回上层时,记得删除当前节点
                return;
            }
        }
        process(root.left,sum,res,temp);
        process(root.right,sum,res,temp);
        temp.remove(temp.size()-1);  // 返回上层时,记得删除当前节点
    }
}

相关文章

  • leetCode 113 Path Sum2

    关键字:树、深度优先 难度:Medium 题目大意:给定二叉树,找到所有root-to-leaf路径和等于给定su...

  • leetcode-tree-113- Path Sum2

    113. Path Sum II Given a binary tree and a sum, find all ...

  • 113、Path Sum2

    与上一题的不同,不同之处需要改变的地方,因为改变而需要注意的地方。 与上一题不同之处 这一题相对于112题,题目增...

  • 113. Path Sum II

    113. Path Sum II 题目: https://leetcode.com/problems/path-s...

  • lint0376. Binary Tree Path Sum

    对应LeetCode 113. Path Sum II打印出所有从根到叶子的路径和等于target的路径Given...

  • LeetCode 113 [Path Sum II]

    原题 给出一个二叉树和一个sum, 找出所有存在的自根节点到叶节点的路径,如果路径和等于sum 样例给出如下二叉树...

  • 【Leetcode】113—Path Sum II

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

  • Leetcode 113 Path Sum II

    题目链接:113. Path Sum II 题目描述 Given a binary tree and a sum,...

  • Leetcode-113Path Sum II

    113. Path Sum II Given a binary tree and a sum, find all ...

  • Leetcode113.Path Sum II

    Given a binary tree and a sum, find all root-to-leaf path...

网友评论

      本文标题:leetCode 113 Path Sum2

      本文链接:https://www.haomeiwen.com/subject/gedzpctx.html