Thursday, September 10, 2020

Convert Sorted List to Binary Search Tree

Problem: Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.

Approach: Use bottom up; kind of inorder traversal.


        public BinarySearchTree(LinkedList sortedList)

        {

            if (sortedList?.Head != null)

            {

                LinkedListNode listNode = sortedList.Head;

                this.Root = this.SortedListToBST(ref listNode, sortedList.Count());

            }

        }


        private BinaryTreeNode SortedListToBST(ref LinkedListNode listNode, int count)

        {

            if (count <= 0)

            {

                return null;

            }

            BinaryTreeNode left = this.SortedListToBST(ref listNode, count / 2);

            BinaryTreeNode root = new BinaryTreeNode(listNode.Value);

            root.LeftNode = left;

            listNode = listNode.Next;

            root.RightNode = this.SortedListToBST(ref listNode, count - count / 2 - 1);

            return root;

        }

No comments:

Post a Comment