Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- void Main()
- {
- var inputTree = new Tree<char>('a',
- new Tree<char>('b',
- null,
- new Tree<char>('c',
- null,
- null)
- ),
- new Tree<char>('d',
- null,
- null)
- );
- var outputTree = Rebuild(inputTree);
- outputTree.Dump();
- Debug.Assert(outputTree.Value == 1, "1");
- Debug.Assert(outputTree.Left.Value == 2, "2");
- Debug.Assert(outputTree.Right.Value == 3, "3");
- Debug.Assert(outputTree.Left.Right.Value == 4, "4");
- Debug.Assert(outputTree.Left.Left == null, "a");
- Debug.Assert(outputTree.Left.Right.Left == null, "b");
- Debug.Assert(outputTree.Left.Right.Right == null, "c");
- Debug.Assert(outputTree.Right.Left == null, "d");
- Debug.Assert(outputTree.Right.Right == null, "e");
- }
- Tree<int> Rebuild<T>(Tree<T> inputTree)
- {
- return InternalRebuild(1, null, inputTree);
- }
- Tree<int> InternalRebuild<T>(int? value, int? sibling, Tree<T> inputTree)
- {
- if (inputTree == null)
- return null;
- var max = Math.Max(value.Value, sibling.GetValueOrDefault());
- var lv = inputTree.Left == null ? (int?) null : max + 1;
- var rv = inputTree.Right == null ? (int?) null : max + (lv == null ? 1 : 2);
- return new Tree<int>(value.Value,
- InternalRebuild(lv, rv, inputTree.Left),
- InternalRebuild(rv, lv, inputTree.Right));
- }
- // Define other methods and classes here
- public class Tree<T>
- {
- public T Value { get; private set; }
- public Tree<T> Left { get; private set; }
- public Tree<T> Right { get; private set; }
- public Tree(T value, Tree<T> left, Tree<T> right)
- {
- Value = value;
- Left = left;
- Right = right;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment