标签: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 }
标签:null example public dfs ini treenode private val tco
原文地址:http://www.cnblogs.com/liangmou/p/7855787.html