public string ConvertWithoutUsingAdditionDataStructure(BiNode root) { BiNode result = ConvertMethod2(root); return(ConvertLinkedlistToString(result)); }
public string ConvertUsingAdditionDataStructure(BiNode root) { NodePair result = ConvertMethod1(root); return(ConvertLinkedlistToString(result.Head)); }
public BiNode(int data, BiNode left, BiNode right) { this.Data = data; this.Node1 = left; this.Node2 = right; }
public NodePair(BiNode head, BiNode tail) { this.Head = head; this.Tail = tail; }
/* This is the recursive function that converts the binary tree to linked list and returns the BiNode which is circular */ //makes the result circular //UPDATE: //Here is the logic // partition 1 + root + partition 3 //(Head to tail) + root + (head to tail) //Make it circular - connect tail of part3 to head of part1 and vice versa //If either of the part is null //If part1 is null - connect tail of part3 to root //if part3 is null - connect root to part1 //dubug the code to understand //update: do revision often public BiNode ConvertToCircular(BiNode root) { if (root == null) { return(null); } //Part1 maintains the head and builds the list forward ..here it is circular BiNode part1 = ConvertToCircular(root.Node1); //part3 maintains the head of the second partition..and the result node is circular BiNode part3 = ConvertToCircular(root.Node2); if (part1 == null && part3 == null) { //if both part1 and part3 are null make the root circular and return root.Node1 = root; root.Node2 = root; return(root); } //tail3 maintain the tail of the sec partition..part3.node1 will be tail bczo it is circular BiNode tail3 = (part3 == null) ? root : part3.Node1; /* join the left to root to form this fashion //(Head to tail) + root + (head to tail) */ if (part1 == null) { //here the logic is hard //part3.node1 will be the tail and we are adding tail + root to make it circular //no worries somewhere in the below root will be added before tail.and will make it as root + tail + root //For eg think of this ////5//// ////////////////////////////////6// ////////////////////////////////////7 //for R(5) part1 = null and part3 = 6 <-> 7 and circular //6,7, 5 Concat(part3.Node1, root); } else { //if part1 is not null //part1.node1 will be the tail of part1 bcoz of circular nature //add the tail of first partition to the root Concat(part1.Node1, root); //straight forward } //note not null has logic and the null code is to make circular /* join the right to root to form this fashion //(Head to tail) + root + (head to tail) */ if (part3 == null) { Concat(root, part1); } else { //(Head to tail) + root + (head to tail) Concat(root, part3); } /* join right to left */ ///we did the circular logic for null if both are not null..make it circular here if (part1 != null && part3 != null) { Concat(tail3, part1); } //return the head of the circular linked list return(part1 == null ? root : part1); }