LeetCode | Path-Sum II

题目描述

 

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 andsum = 22,
              5
             / \
            4   8
           /   / \
          11  13  4
         /  \    / \
        7    2  5   1

return

[
   [5,4,11,2],
   [5,8,4,5]
]

题目意思: 求根节点到叶子几点路径和为sum的全部路径。

 1 import java.util.*;
 2 /**
 3  * Definition for binary tree
 4  * public class TreeNode {
 5  *     int val;
 6  *     TreeNode left;
 7  *     TreeNode right;
 8  *     TreeNode(int x) { val = x; }
 9  * }
10  */
11 public class Solution {
12     ArrayList<ArrayList<Integer>> listPath = new ArrayList<>();
13     public ArrayList<ArrayList<Integer>> pathSum(TreeNode root, int sum) {
14         
15         getPath(root, sum, new ArrayList<Integer>());
16         return listPath;
17     }
18     
19     public void getPath(TreeNode root, int sum, ArrayList<Integer> path) {
20         if (root == null) {
21             return;
22         }
23         sum -= root.val; //首先将sum减去当前节点的值
24         if (root.left == null && root.right==null) {//判断该节点是否为叶子节点
25             if (sum == 0) {//该节点为叶子且sum为0,满足条件
26                 path.add(root.val);
27                 listPath.add(new ArrayList<Integer>(path));
28                 path.remove(path.size()-1);
29             }
30             return;
31         }
32         path.add(root.val); //path添加当前值
33         getPath(root.left, sum, path);    //左子树进行上面操作
34         getPath(root.right, sum, path); //右子树进行上面操作
35         path.remove(path.size()-1);    //该节点的左右子树都操作完后,删除该节点在path上的值
36     }
37 }

 

posted @ 2017-06-28 16:08  huangyichun  阅读(169)  评论(0编辑  收藏  举报