首页 > 其他 > 详细

Path Sum II 解答

时间:2015-10-01 00:32:25      阅读:201      评论:0      收藏:0      [点我收藏+]

Question

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]
]

Solution

Traditional way, use DFS and recursion.

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     public List<List<Integer>> pathSum(TreeNode root, int sum) {
12         List<List<Integer>> result = new ArrayList<List<Integer>>();
13         List<Integer> prevList = new ArrayList<Integer>();
14         dfs(root, sum, result, prevList);
15         return result;   
16     }
17     
18     private void dfs(TreeNode root, int target, List<List<Integer>> result, List<Integer> prevList) {
19         if (root == null)
20             return;
21         prevList.add(root.val);
22         
23         if (root.left == null && root.right == null) {
24             if (root.val == target)
25                 result.add(new ArrayList<Integer>(prevList));
26         } else {
27             List<Integer> tmpList2 = new ArrayList<Integer>(prevList);
28             if (root.left != null)
29                 dfs(root.left, target - root.val, result, prevList);
30             if (root.right != null)
31                 dfs(root.right, target - root.val, result, tmpList2);
32         }
33         
34     }
35 }

 

Path Sum II 解答

原文:http://www.cnblogs.com/ireneyanglan/p/4850528.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!