Leetcode 113: Path Sum II

Posted Keep walking

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 113: 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 and sum = 22,

              5
             /             4   8
           /   /           11  13  4
         /  \    /         7    2  5   1

return

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

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     public int val;
 5  *     public TreeNode left;
 6  *     public TreeNode right;
 7  *     public TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     public IList<IList<int>> PathSum(TreeNode root, int sum) {
12         var results = new List<IList<int>>();
13         DFS(root, 0, sum, new List<int>(), results);
14         return results;
15     }
16     
17     private void DFS(TreeNode node, int cur, int sum, IList<int> path, IList<IList<int>> results)
18     {
19         if (node == null) return;
20         path.Add(node.val);
21             
22         if (node.left == null && node.right == null)
23         {
24             if (cur + node.val == sum)
25             {
26                 results.Add(new List<int>(path));
27             }
28         }
29         else
30         {
31             DFS(node.left, cur + node.val, sum, path, results);
32             DFS(node.right, cur + node.val, sum, path, results);    
33         }
34                
35         path.RemoveAt(path.Count - 1);
36     }
37 }

 




以上是关于Leetcode 113: Path Sum II的主要内容,如果未能解决你的问题,请参考以下文章

leetcode [113]Path Sum II

[LeetCode] 113. Path Sum II 路径和 II

LeetCode 113. Path Sum II

Leetcode 113: Path Sum II

LeetCode 113:Path Sum II

LeetCode113 Path Sum II