Convert Sorted Array to Balanced Binary Search Tree (BST)
2015-01-18 19:01 李涛的技术博客 阅读(128) 评论(0) 编辑 收藏 举报(http://leetcode.com/2010/11/convert-sorted-array-into-balanced.html)
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
Code:
BinaryTree* sortedArrayToBST(int arr[], int start, int end) { if (start > end) return NULL; int mid = start + (end - start) / 2; BinaryTree* node = new BinaryTree(arr[mid]); node->left = sortedArrayToBST(arr, start, mid-1); node->right = sortedArrayToBST(arr, mid+1, end); return node; } BinaryTree* sortedArrayToBST(int arr[], int n) { return sortedArrayToBST(arr, 0, n-1); }