Advertisement
KAMEN1973

SumDfs

Sep 26th, 2020
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.08 KB | None | 0 0
  1. public List<Tree<T>> SubTreesWithGivenSum(int sum)
  2. {
  3. List<Tree<T>> subtreesWithSum = new List<Tree<T>>();
  4.  
  5. this.GetSubtreesWithSum(this, subtreesWithSum, sum);
  6.  
  7. return subtreesWithSum;
  8. }
  9.  
  10. private void GetSubtreesWithSum(Tree<T> tree, List<Tree<T>> subtreesWithSum, int sum)
  11. {
  12. //int treeSum = this.GetTreeSum(tree);
  13. int treeSum = this.GetTreeSumDfs(tree, 0);
  14.  
  15. if (treeSum == sum)
  16. {
  17. subtreesWithSum.Add(tree);
  18. }
  19.  
  20. foreach (Tree<T> child in tree.Children)
  21. {
  22. this.GetSubtreesWithSum(child, subtreesWithSum, sum);
  23. }
  24. }
  25.  
  26. private int GetTreeSumDfs(Tree<T> tree, int sum)
  27. {
  28. sum += Convert.ToInt32(tree.Key);
  29.  
  30. foreach (Tree<T> child in tree.Children)
  31. {
  32. sum += Convert.ToInt32(child.Key);
  33. this.GetTreeSumDfs(child, sum);
  34. }
  35.  
  36. return sum;
  37. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement