DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Aniruddha has posted 40 posts at DZone. View Full User Profile

Build Binary Search Tree - C#

06.05.2012
| 5640 views |
  • submit to reddit
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<int> _result = new List<int>();
            for (int i = start; i <= end; i++)
            {
                _result.Add(array[i]);
            }
            return _result.ToArray();
        }

Build Binary Search Tree - C#

Efficiency: O(n)