leetCode 113 Path Sum2

  • 关键字:树、深度优先
  • 难度: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> pathSum(TreeNode root, int sum) {
        List> res = new ArrayList<>();
        List temp = new ArrayList<>();
          process(root,sum,res,temp);
        return res;

    }

    public void process(TreeNode root, int sum, List>res,Listtemp ) {
        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)