Example #1
0
        public KarthicBTNode <int> BuildTreeUsingMap(Dictionary <int, List <int> > map, int rootvalue)
        {
            KarthicBTNode <int> node = new KarthicBTNode <int>(rootvalue);

            int childs = 0;

            if (map.ContainsKey(rootvalue))
            {
                childs = map[rootvalue].Count;
            }

            if (childs == 0)
            {
                return(node);
            }

            node.Left = BuildTreeUsingMap(map, map[rootvalue][0]);

            if (childs == 2)
            {
                node.Right = BuildTreeUsingMap(map, map[rootvalue][1]);
            }


            return(node);
        }
Example #2
0
        //Logic
        //We check if the noofchilds of the current node with k value
        //if its equal return the current node
        //greater search on the right child (k - leftchilds)
        //lesser it has to the left side so search on the node.left for k

        //update 5/9 below code is for kth largest
        public KarthicBTNode <int> FindkthSmallestNodeByChildNo(KarthicBTNode <int> root, int k)
        {
            if (root == null)
            {
                return(null);
            }

            int leftchilds    = root.LeftChilds;
            int rootandchilds = leftchilds + 1; //this value is inclusive of the root node and its left childs

            //int rightchilds = root.RightChilds;

            if (k == rootandchilds)
            {
                return(root);
            }
            else if (k < rootandchilds)
            {
                return(findKthSmallesIterative(root.Left, k));
            }
            else
            {
                return(findKthSmallesIterative(root.Right, k - rootandchilds));
            }
        }
Example #3
0
        //Logic:
        //Get to the leftmost of the tree untill it reaches null and push the left node to the stack while doing
        //After reaching null pop the top on the stack which will be the first smallest check for the k value when popped up
        //If k not found which mean we need to find the next smalles element
        //Since the left child is null the next smallest will be leftmost of the rightsubtree so check if it has rightsubtree
        //If rightsubtree exists get the leftmost of that untill it reaches null
        //If rightsubtree is null we pop the next element which would be the next smallest

        public KarthicBTNode <int> findKthSmallesIterative(KarthicBTNode <int> node, int K)
        {
            Stack <KarthicBTNode <int> > stack = new Stack <KarthicBTNode <int> >();
            int i = 1;

            while (stack.Count != 0 || node != null)
            {
                if (node == null)
                {
                    node = stack.Pop();
                    if (i == K)
                    {
                        return(node);
                    }
                    ++i;
                    node = node.Right;
                }
                if (node != null)
                {
                    stack.Push(node);
                    node = node.Left;
                }
            }


            return(null);
        }
Example #4
0
        private void CreateLinkedListForNodes(KarthicBTNode <int> current, List <LinkedList <KarthicBTNode <int> > > colllist, int level)
        {
            //Base case for recursion
            if (current == null)
            {
                return;
            }
            //we shouldn't create new..If we need new linkedlist add that reference or add to the existing reference
            LinkedList <KarthicBTNode <int> > nodelist = null;

            //if count is equal to level..level are in o based index where size is not.. if count = 0 and level = o we need to add one linkedlist to store the values
            if (colllist.Count == level)
            {
                nodelist = new LinkedList <KarthicBTNode <int> >();
                colllist.Add(nodelist);
            }
            else
            {
                //If the count = 3 and level = 1..we need to get the reference of level 1
                nodelist = colllist[level];
            }

            //Pre-order traversal

            //current
            nodelist.AddLast(current);

            //left children
            CreateLinkedListForNodes(current.Left, colllist, level + 1);

            //right children
            CreateLinkedListForNodes(current.Right, colllist, level + 1);
        }
Example #5
0
        public string PreOrderTraversal(KarthicBTNode <int> currentnode, bool InsertZerofornull)
        {
            //Base case
            if (currentnode == null)
            {
                if (InsertZerofornull)
                {
                    sb.Append(0).Append(',');
                }
                return(sb.ToString());
            }

            //print current node
            sb.Append(currentnode.Data).Append(',');

            //Traverse on left childresn

            PreOrderTraversal(currentnode.Left, true);

            //Traverse on right childrens

            PreOrderTraversal(currentnode.Right, true);

            return(sb.ToString());
        }
Example #6
0
        public bool IsBSTOptimalSolution(KarthicBTNode <int> current, int min, int max)
        {
            //we can use any traversal.. i am using  in-order
            //base case
            if (current == null)
            {
                return(true);
            }

            //current data should be always greater than or equal min

            if (current.Data <= min || current.Data > max)
            {
                return(false);
            }

            //For left children Min value is Parent's Min value (excluding) and Max value is parent.Data (including..can be equal)
            if (IsBSTOptimalSolution(current.Left, min, current.Data) == false)
            {
                return(false);
            }

            //For right children Min value should be greater than parent.Data and Max value is parent's max (
            if (IsBSTOptimalSolution(current.Right, current.Data, max) == false)
            {
                return(false);
            }


            return(true);
        }
Example #7
0
        public static bool IsBalanced(KarthicBTNode <int> node)
        {
            //For any node in the tree, the difference btw the height of left and height of right should not be greater than 1..
            //If it greater than 1 it is not balanced tree else it is balanced tree

            //Base case
            if (node == null)
            {
                return(true);
            }

            int leftheight  = GetHeight(node.Left);
            int rightheight = GetHeight(node.Right);

            int difference = Math.Abs(leftheight - rightheight);

            if (difference > 1)
            {
                return(false);
            }
            else
            {
                return(IsBalanced(node.Left) && IsBalanced(node.Right));
            }
        }
Example #8
0
        private void button8_Click(object sender, EventArgs e)
        {
            //Things to ask interviewer
            //1) Is it BST OR BINARY tree?. If it is bst we can use the value and compare

            //bst code


            KarthicBST <int> tree = TreeHelper.SetUpBinarySearchTree();

            StringBuilder sb = new StringBuilder();

            tree.InOrderTraversal(tree.Root, ref sb);

            string check = sb.ToString();


            KarthicBTNode <int> node1 = tree.Find(4, tree.Root);
            KarthicBTNode <int> node2 = tree.Find(7, tree.Root);
            KarthicBTNode <int> root  = tree.Root;

            KarthicBTNode <int> result2 = tree.FindFirstCommonAncestorForOnlyBST(tree.Root, tree.Find(4, tree.Root), tree.Find(103, tree.Root));



            //2) Is the parent node is given...

            //If the parent node is given and addition datastructure is allowed

            //Take one node and mark all the path visited as true from root..either modify tree node struc or use ht
            //Take another node and keep track of last visited..when we reach first non-visited path then last visited will be ancestor

            //if the parent node is goven and addition datasturc not allowed
        }
Example #9
0
        //public KarthicBTNode<int> Insert(int value)
        //{
        //    return Insert(value, this.Root);
        //}


        public KarthicBTNode <int> Insert(int value, KarthicBTNode <int> runner)
        {
            //base case
            if (runner == null)
            {
                return(new KarthicBTNode <int>(value));
            }

            if (value == runner.Data)
            {
                throw new Exception("Data already exists");
            }
            else if (value < runner.Data)
            {
                //move toward left childrens
                KarthicBTNode <int> node = Insert(value, runner.Left);
                node.Parent = runner;
                runner.Left = node;
            }
            else
            {
                //move toward right children
                KarthicBTNode <int> node = Insert(value, runner.Right);
                node.Parent  = runner;
                runner.Right = node;
            }

            Size++;

            return(runner);
        }
Example #10
0
        public List <string> FindSum(KarthicBTNode <int> node, int sum, ArrayList buffer, int level, List <string> output)
        {
            if (node == null)
            {
                return(output);
            }

            buffer.Add(node.Data);
            int temp = sum;

            //check for paths
            for (int i = level; i > -1; i--)
            {
                temp = temp - (int)buffer[i];
                //if path found
                if (temp == 0)
                {
                    output = PrintOutput(buffer, level, i, output);
                }
            }

            ArrayList leftcopy  = (ArrayList)buffer.Clone();
            ArrayList rightcopy = (ArrayList)buffer.Clone();

            output = FindSum(node.Left, sum, leftcopy, level + 1, output);

            output = FindSum(node.Right, sum, rightcopy, level + 1, output);


            return(output);
        }
Example #11
0
        public void FindSum(KarthicBTNode <int> node, int sum, ArrayList buffer, int level)
        {
            if (node == null)
            {
                return;
            }


            if (node.Data == 12)
            {
                string s = "Test";
            }
            buffer.Add(node.Data);


            int temp = sum;

            //check for paths
            for (int i = level; i > -1; i--)
            {
                temp = temp - (int)buffer[i];
                //if path found
                if (temp == 0)
                {
                    PrintOutput(buffer, level, i, new List <string>());
                }
            }

            ArrayList leftcopy  = (ArrayList)buffer.Clone();
            ArrayList rightcopy = (ArrayList)buffer.Clone();

            FindSum(node.Left, sum, leftcopy, level + 1);

            FindSum(node.Right, sum, rightcopy, level + 1);
        }
Example #12
0
        public List <string> FindSumUsingArray(KarthicBTNode <int> node, int sum, int[] buffer, int level, List <string> output)
        {
            if (node == null)
            {
                return(output);
            }

            //buffer.Add(node.Data);
            buffer[level] = node.Data;

            int temp = sum;

            //check for paths
            for (int i = level; i > -1; i--)
            {
                temp = temp - (int)buffer[i];
                //if path found
                if (temp == 0)
                {
                    output = PrintOutputArray(buffer, level, i, output);
                }
            }


            output = FindSumUsingArray(node.Left, sum, buffer, level + 1, output);

            output = FindSumUsingArray(node.Right, sum, buffer, level + 1, output);


            return(output);
        }
Example #13
0
        //This will first add root node and then add all its left and right childrent by recurssion..
        //At the end of recurssion it will return the root node
        //Important: Base case and calculation of the middle pointer are important
        public KarthicBTNode <int> AddToTreeMinimalHeight(int[] array, int startpointer, int endpointer)
        {
            //In  order to get a tree with minimal height for the given ascending order array
            //1) Take the array and set the middle element of the array as the node
            //2) Take the left of the middle node that is (o to middle-1) as left childrens for this node
            //3) Take the right of the middle node that is (middle+1 to length-1) as the right childresn for this node
            //Recurrse this logic for every node and recurrsion has to stop on the last node


            //Base case.. stop the recurssion if end value is lesser than start value
            if (endpointer < startpointer)
            {
                //Base return
                return(null);
            }
            //we can't calculate the middle based on the array length here..bcoz that is constant..only the start and end changes
            //Round the value if the total is odd 7/2 = 4
            int middlepointer = (startpointer + endpointer) / 2;

            //Create node witht the middle element
            KarthicBTNode <int> node = new KarthicBTNode <int>(array[middlepointer]);

            //Input : 11, 22, 33, 44, 55, 66, 77
            //The last of the left children will have
            //11(node).left = AddToTreeMinimalHeight(array, 0, (0 -1 ));
            //11(node).Right = AddToTreeMinimalHeight(array, 0+1, (0 -1 ));
            //add left children this node
            node.Left = AddToTreeMinimalHeight(array, startpointer, middlepointer - 1);
            //add right children to this node
            node.Right = AddToTreeMinimalHeight(array, middlepointer + 1, endpointer);


            return(node);
        }
Example #14
0
 public KarthicBTNode(T value)
 {
     this.Data = value;
     Left      = null;
     Right     = null;
     Parent    = null;
 }
        /* Given a binary tree, print its nodes in reverse level order */
        bool isIsomorphic(KarthicBTNode <int> n1, KarthicBTNode <int> n2)
        {
            // Both roots are NULL, trees isomorphic by definition
            if (n1 == null && n2 == null)
            {
                return(true);
            }

            // Exactly one of the n1 and n2 is NULL, trees not isomorphic
            if (n1 == null || n2 == null)
            {
                return(false);
            }

            if (n1.Data != n1.Data)
            {
                return(false);
            }

            // There are two possible cases for n1 and n2 to be isomorphic
            // Case 1: The subtrees rooted at these nodes have NOT been "Flipped".
            // Both of these subtrees have to be isomorphic, hence the &&
            // Case 2: The subtrees rooted at these nodes have been "Flipped"
            return
                ((isIsomorphic(n1.Left, n2.Left) && isIsomorphic(n1.Right, n2.Right)) ||
                 (isIsomorphic(n1.Left, n2.Right) && isIsomorphic(n1.Right, n2.Left)));
        }
        public CustomNode <int> BuildSpecialTreeFromPreorderArray(int[] preArray, char[] LeafArray, int index)
        {
            if (index == preArray.Length)
            {
                CustomNode <int> nodenull = new CustomNode <int>();
                nodenull.treenode   = null;
                nodenull.StartIndex = index;
                return(nodenull);
            }

            KarthicBTNode <int> node = new KarthicBTNode <int>(preArray[index]);
            int actualnodeindex      = index;

            index++;

            CustomNode <int> custom = new CustomNode <int>();

            custom.treenode   = node;
            custom.StartIndex = index;
            //No leaf node
            if (LeafArray[actualnodeindex] == 'N')
            {
                CustomNode <int> ltree = BuildSpecialTreeFromPreorderArray(preArray, LeafArray, index);
                custom.treenode.Left = ltree.treenode;

                CustomNode <int> rtree = BuildSpecialTreeFromPreorderArray(preArray, LeafArray, ltree.StartIndex);
                custom.treenode.Right = rtree.treenode;

                custom.StartIndex = rtree.StartIndex;
            }


            return(custom);
        }
Example #17
0
        public KarthicBTNode <int> FindFirstCommonAncestorHelper(KarthicBTNode <int> root, KarthicBTNode <int> node1, KarthicBTNode <int> node2)
        {
            //Logic to find common ancestors
            //Check if the node1 and node2 is on the same side (left or right) of the root..
            //If they are on the different side then the root is the common ancestor...If not recurse till we get this condition or till we meet the end base

            if (root == null)
            {
                return(null);
            }
            //we already checked whether node1 and node2 exists on the root but haven't checked it is equal to root
            if (root == node1 || root == node2)
            {
                return(root);
            }

            bool IsNode1OnLeftSide = FindDescendants(root, node1);
            bool IsNode2OnLeftSide = FindDescendants(root, node2);

            //if they are on both sides..we are done ..just return the root
            if (IsNode1OnLeftSide != IsNode2OnLeftSide)
            {
                return(root);
            }

            //if the code comes here means they are on the same side..get the side and continue the recurse

            KarthicBTNode <int> childnode = IsNode1OnLeftSide ? root.Left : root.Right;

            return(FindFirstCommonAncestorHelper(childnode, node1, node2));
        }
Example #18
0
        public bool FindDescendants(KarthicBTNode <int> runner, KarthicBTNode <int> node)
        {
            //base case
            if (runner == null || node == null)
            {
                return(false);
            }

            //check for current
            if (runner == node)
            {
                return(true);
            }

            //This code is equivalent to the below lines
            //return FindDescendants(runner.Left, node) || FindDescendants(runner.Right, node);

            if (FindDescendants(runner.Left, node))
            {
                return(true);
            }

            if (FindDescendants(runner.Right, node))
            {
                return(true);
            }


            return(false);
        }
Example #19
0
        /*  refer gayle new edition oag 258...not time now
         *
         * Time 0(t) where t is size of the substree in this common ancestor worst case 0(n)
         *
         */

        public KarthicBTNode <int> FindFirstCommonAncestorUsingParent(KarthicBTNode <int> root, KarthicBTNode <int> node1, KarthicBTNode <int> node2)
        {
            if (root == null)
            {
                return(null);
            }

            //make sure both node1 and node2 exsits in root
            if (FindDescendants(root, node1) == false || FindDescendants(root, node2) == false)
            {
                return(null);
            }

            if (FindDescendants(node1, node2))
            {
                return(node1);//node1 contains node2
            }

            if (FindDescendants(node2, node1))
            {
                return(node2);
            }

            KarthicBTNode <int> sibling = FindSibling(node1);
            KarthicBTNode <int> parent  = node1.Parent;

            //if node1 and node2 is missing in root mean this code will run indefinit but here we alredy check that root has node1 and node2
            while (FindDescendants(sibling, node2) == false)
            {
                sibling = FindSibling(parent);
                parent  = parent.Parent;
            }
            //when code come here means we found descendant
            return(parent);
        }
Example #20
0
        // A function to print all right boundry nodes, except a leaf node
        // Print the nodes in BOTTOM UP manner
        private void PrintRightBorder(KarthicBTNode <int> node, StringBuilder sb)
        {
            if (node == null)
            {
                return;
            }

            if (node.Left == null && node.Right == null)
            {
                return;
            }

            if (node.Right != null)
            {
                PrintRightBorder(node.Right, sb);
                sb.Append(node.Data).Append(",");
            }
            //if (node != null)
            //{
            //    if (node.Right != null)
            //    {

            //        sb.Append(node.Data).Append(",");
            //        PrintRightBorder(node.Right, sb);

            //    }
            //}
        }
Example #21
0
        /*
         * Given a tree and a sum, return true if there is a path from the root
         * down to a leaf, such that adding up all the values along the path
         * equals the given sum.
         *
         * Strategy: subtract the node value from the sum when recurring down,
         * and check to see if the sum is 0 when you run out of tree (leaf node)
         */
        public bool HasPath(KarthicBTNode <int> node, int sum)
        {
            if (node == null)
            {
                //if (sum == 0)
                //{
                //    return true;
                //}
                //else
                //{
                //    return false;
                //}

                return(sum == 0);
            }

            int subsum = sum - node.Data;

            /* If we reach a leaf node and sum becomes 0 then return true*/
            if (subsum == 0 && node.Left == null && node.Right == null)
            {
                return(true);
            }

            /* otherwise check both subtrees */

            return(HasPath(node.Left, subsum) || HasPath(node.Right, subsum));
        }
Example #22
0
        private void button9_Click(object sender, EventArgs e)
        {
            KarthicBST <int> tree = TreeHelper.SetUpBinarySearchTree();

            StringBuilder sb = new StringBuilder();

            tree.InOrderTraversal(tree.Root, ref sb);

            string check = sb.ToString();


            //Given the node of a bst, find the next node of the given node via in-order traversal

            //In-order traversal  left, current  and right

            //pseudocode
            // public Node Inordersuccessor(node)
            ///   if(node has right subtree)
            ///     return (left most node of right subtree)
            ///   else
            ///     while (n is right of n.parent)
            ///            n = n.parent
            ///       return n.parent
            ///

            KarthicBTNode <int> next = tree.NextInOrderSuccessor(tree.Find(10, tree.Root));
        }
Example #23
0
 //print all left border except the leaf node to avoid duplicates
 private void PrintLeftBorder(KarthicBTNode <int> node, StringBuilder sb)
 {
     if (node.Left != null && node.Right != null)
     {
         sb.Append(node.Data).Append(",");
         PrintLeftBorder(node.Left, sb);
     }
 }
Example #24
0
        public int GetDepth(KarthicBTNode <int> node)
        {
            if (node == null)
            {
                return(0);
            }

            return(1 + Math.Max(GetDepth(node.Left), GetDepth(node.Right)));
        }
Example #25
0
        public KarthicBTNode <int> FindFirstCommonAncestor(KarthicBTNode <int> root, KarthicBTNode <int> node1, KarthicBTNode <int> node2)
        {
            //Check whether both node1 and node2 exsits in root
            if ((!FindDescendants(root, node1)) || (!FindDescendants(root, node2)))
            {
                throw new Exception("node 1 or 2 does not exists");
            }

            return(FindFirstCommonAncestorHelper(root, node1, node2));
        }
Example #26
0
        public bool ContainsTree(KarthicBTNode <int> t1, KarthicBTNode <int> t2)
        {
            //null will be always there is tree so if t2 is null..then t2 is subtree of t1
            if (t2 == null)
            {
                return(true);
            }

            return(CheckSubTree(t1, t2));
        }
Example #27
0
        private void button10_Click(object sender, EventArgs e)
        {
            KarthicBST <int> tree = TreeHelper.SetUpBinarySearchTree();

            int input = Convert.ToInt32(this.textBox4.Text);

            //int input =
            KarthicBTNode <int> result = tree.Find(input, tree.Root);

            //KarthicBTNode<int> result = tree.Find2(input, tree.Root);

            this.textBox6.Text = (result != null) ? "true" : "false";
        }
        //Logic: we check whether the childer is a sum tree and then go back to parents
        //We go to parent only when children is true..and in parent we don't have to calculate sum again..it will be twice as the current.data...

        // The Method 1 uses sum() to get the sum of nodes in left and right subtrees. The method 2 uses following rules to get the sum directly.
        //1) If the node is a leaf node then sum of subtree rooted with this node is equal to value of this node.
        //2) If the node is not a leaf node then sum of subtree rooted with this node is twice the value of this node (Assuming that the tree rooted with this node is SumTree).
        private bool IsSumTreeOptimized(KarthicBTNode <int> root)
        {
            if (root == null)
            {
                return(true);
            }

            if (root.Left == null && root.Right == null)
            {
                return(true);
            }

            if (IsSumTreeOptimized(root.Left) && IsSumTreeOptimized(root.Right))
            {
                int leftsubtreesum   = 0;
                int rightsubstreesum = 0;
                //if (root.Left == null)
                //{
                //    leftsubtreesum = 0;
                //}
                if (root.Left != null)
                {
                    if (IsLeafNode(root.Left))
                    {
                        leftsubtreesum = root.Left.Data;
                    }
                    else
                    {
                        //we alredy know the children is valid sum tree
                        //so the value of child will be twice the current
                        leftsubtreesum = 2 * (root.Left.Data);
                    }
                }
                if (root.Right != null)
                {
                    if (IsLeafNode(root.Right))
                    {
                        rightsubstreesum = root.Right.Data;
                    }
                    else
                    {
                        rightsubstreesum = 2 * (root.Right.Data);
                    }
                }

                return(root.Data == (leftsubtreesum + rightsubstreesum));
            }

            return(false);
        }
        private bool IsLeafNode(KarthicBTNode <int> current)
        {
            if (current == null)
            {
                return(true);
            }

            if (current.Left == null && current.Right == null)
            {
                return(true);
            }

            return(false);
        }
Example #30
0
        public void LevelZigZacTraversal(KarthicBTNode <int> currentnode, StringBuilder sb)
        {
            //Logic: use two stack to make zigzac
            //stack1 - will contain nodes from one direction (left to right)
            //stack2 - will contain nodes from the opposite direction (right to left)


            Stack <KarthicBTNode <int> > stack1   = new Stack <KarthicBTNode <int> >();
            Stack <KarthicBTNode <int> > stack2   = new Stack <KarthicBTNode <int> >();
            KarthicBTNode <int>          current1 = new KarthicBTNode <int>();
            KarthicBTNode <int>          current2 = new KarthicBTNode <int>();

            stack1.Push(currentnode);


            while (stack1.Count != 0 || stack2.Count != 0)
            {
                while (stack1.Count != 0)
                {
                    current1 = stack1.Pop();
                    sb.Append(current1.Data).Append(",");

                    if (current1.Left != null)
                    {
                        stack2.Push(current1.Left);
                    }
                    if (current1.Right != null)
                    {
                        stack2.Push(current1.Right);
                    }
                }

                while (stack2.Count != 0)
                {
                    current2 = stack2.Pop();
                    sb.Append(current2.Data).Append(",");

                    //important visit right children and then left so that we maintain the reverse order

                    if (current2.Right != null)
                    {
                        stack1.Push(current2.Right);
                    }
                    if (current2.Left != null)
                    {
                        stack1.Push(current2.Left);
                    }
                }
            }
        }