Creating a Binary Search Tree from a sorted array

前端 未结 3 1981
醉话见心
醉话见心 2020-12-18 07:50

I am currently checking about coding an algorithms. If we have the following case:

Given a sorted (increasing order) array with unique integer elements, wrote an alg

3条回答
  •  失恋的感觉
    2020-12-18 08:30

    • get the middle of the array and make it as root
    • recursively do the same for the left half and the right half
      • get the middle of the left half and make it the left child of the root
      • get the middle of the right half and make it the right child of the root

        public TreeNode Convert(int[] array)
        {
            if (array == null || array.Length == 0)
            {
                return null;
            }
    
            return Convert(array, 0, array.Length - 1);
        }
    
        private static TreeNode Convert(int[] array, int lo, int hi)
        {
            if (lo > hi)
            {
                return null;
            }
    
            int mid = lo + (hi - lo) / 2;
            var root = new TreeNode(array[mid]);
            root.Left = Convert(array, lo, mid - 1);
            root.Right = Convert(array, mid + 1, hi);
            return root;
        }
    

    Time Complexity: O(n)

    from CodeStandard

提交回复
热议问题