码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode 113: Path Sum II

时间:2017-11-18 11:07:42      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:null   example   public   dfs   ini   treenode   private   val   tco   

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

标签:null   example   public   dfs   ini   treenode   private   val   tco   

原文地址:http://www.cnblogs.com/liangmou/p/7855787.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!