Guest User

Untitled

a guest
Jun 23rd, 2014
319
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.77 KB | None | 0 0
  1. void Main()
  2. {
  3.     var inputTree = new Tree<char>('a',
  4.         new Tree<char>('b',
  5.             null,
  6.             new Tree<char>('c',
  7.                 null,
  8.                 null)
  9.             ),
  10.         new Tree<char>('d',
  11.             null,
  12.             null)
  13.     );
  14.    
  15.     var outputTree = Rebuild(inputTree);
  16.    
  17.     outputTree.Dump();
  18.    
  19.     Debug.Assert(outputTree.Value == 1, "1");
  20.     Debug.Assert(outputTree.Left.Value == 2, "2");
  21.     Debug.Assert(outputTree.Right.Value == 3, "3");
  22.     Debug.Assert(outputTree.Left.Right.Value == 4, "4");
  23.    
  24.     Debug.Assert(outputTree.Left.Left == null, "a");
  25.     Debug.Assert(outputTree.Left.Right.Left == null, "b");
  26.     Debug.Assert(outputTree.Left.Right.Right == null, "c");
  27.     Debug.Assert(outputTree.Right.Left == null, "d");
  28.     Debug.Assert(outputTree.Right.Right == null, "e");
  29. }
  30.  
  31. Tree<int> Rebuild<T>(Tree<T> inputTree)
  32. {
  33.     return InternalRebuild(1, null, inputTree);
  34. }
  35.  
  36. Tree<int> InternalRebuild<T>(int? value, int? sibling, Tree<T> inputTree)
  37. {
  38.     if (inputTree == null)
  39.         return null;
  40.    
  41.     var max = Math.Max(value.Value, sibling.GetValueOrDefault());
  42.     var lv = inputTree.Left == null ? (int?) null : max + 1;
  43.     var rv = inputTree.Right == null ? (int?) null : max + (lv == null ? 1 : 2);
  44.    
  45.     return new Tree<int>(value.Value,
  46.         InternalRebuild(lv, rv, inputTree.Left),
  47.         InternalRebuild(rv, lv, inputTree.Right));
  48. }
  49.  
  50. // Define other methods and classes here
  51. public class Tree<T>
  52. {
  53.     public T Value { get; private set; }
  54.     public Tree<T> Left { get; private set; }
  55.     public Tree<T> Right { get; private set; }
  56.    
  57.     public Tree(T value, Tree<T> left, Tree<T> right)
  58.     {
  59.         Value = value;
  60.         Left = left;
  61.         Right = right;
  62.     }
  63. }
Advertisement
Add Comment
Please, Sign In to add comment