Guest User

Untitled

a guest
Feb 24th, 2018
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.99 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7.  
  8. namespace BinarySearchTreeSplitTree
  9. {
  10. /// <summary>
  11. /// The algorith is written for my mock interview to test the candidate recursive solution.
  12. /// Leetcode 776: Split binary search tree
  13. /// </summary>
  14. class Program
  15. {
  16. internal class TreeNode
  17. {
  18. public int Value { get; set; }
  19. public TreeNode Left { get; set; }
  20. public TreeNode Right { get; set; }
  21.  
  22. public TreeNode(int number)
  23. {
  24. Value = number;
  25. }
  26. }
  27.  
  28. static void Main(string[] args)
  29. {
  30. RunTestcase();
  31. }
  32.  
  33. public static void RunTestcase()
  34. {
  35. // work on root node
  36. var node20 = new TreeNode(20);
  37.  
  38. // work on level 1
  39. var node9 = new TreeNode(9);
  40. var node25 = new TreeNode(25);
  41.  
  42. // work on connection from root node to its children
  43. node20.Left = node9;
  44. node20.Right = node25;
  45.  
  46. // work on level 2
  47. var node5 = new TreeNode(5);
  48. var node12 = new TreeNode(12);
  49.  
  50. // work on connection from level 1's nodes to their children
  51. node9.Left = node5;
  52. node9.Right = node12;
  53.  
  54. // work on level 3
  55. var node11 = new TreeNode(11);
  56. var node14 = new TreeNode(14);
  57.  
  58. // work on connection from level 2's nodes to their children
  59. node12.Left = node11;
  60. node12.Right = node14;
  61.  
  62. var successor1 = SplitTree(node20, 15);
  63.  
  64. var successor2 = SplitTree(node20, 9);
  65.  
  66. var successor3 = SplitTree(node20, 11);
  67. }
  68.  
  69. /// <summary>
  70. /// Split binary search tree
  71. /// First tree with node value small and equal to the target value.
  72. /// Second tree with node value greater than the target value.
  73. /// </summary>
  74. /// <param name="root"></param>
  75. /// <param name="givenNode"></param>
  76. /// <returns></returns>
  77. public static TreeNode[] SplitTree(TreeNode root, int target)
  78. {
  79. if (root == null)
  80. {
  81. return new TreeNode[2];
  82. }
  83.  
  84. var splitLeftSubTree = root.Value > target;
  85.  
  86. if (splitLeftSubTree)
  87. {
  88. var childTrees = SplitTree(root.Left, target);
  89.  
  90. var tmp = childTrees[1];
  91. childTrees[1] = root;
  92. childTrees[1].Left = tmp;
  93.  
  94. return childTrees;
  95. }
  96. else
  97. {
  98. var childTrees = SplitTree(root.Right, target);
  99.  
  100. var tmp = childTrees[0];
  101.  
  102. childTrees[0] = root;
  103. childTrees[0].Right = tmp;
  104.  
  105. return childTrees;
  106. }
  107. }
  108. }
  109. }
Add Comment
Please, Sign In to add comment