Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Build Binary Search Tree - C#

DZone's Guide to

Build Binary Search Tree - C#

·
Free Resource

Build Binary Search Tree - C#

Efficiency: O(n)

 

public static BinaryTreeNode BuildBinarySearchTree(int[] sortedArray)
        {
            if (sortedArray.Length == 0)
                return null;

            int _mid = sortedArray.Length / 2;
            BinaryTreeNode _root = new BinaryTreeNode(sortedArray[_mid]);
            int[] _left = GetSubArray(sortedArray, 0, _mid - 1);
            int[] _right = GetSubArray(sortedArray, _mid + 1, sortedArray.Length - 1);
            _root.Left = BuildBinarySearchTree(_left);
            _root.Right = BuildBinarySearchTree(_right);

            return _root;
        }


        public int[] GetSubArray(int[] array, int start, int end)
        {
            List
 
   _result = new List
  
   ();
            for (int i = start; i <= end; i++)
            {
                _result.Add(array[i]);
            }
            return _result.ToArray();
        }
  
 
Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}