diff --git a/Convert-Sorted-Array-to-Binary-Search-Tree/Solution.cpp b/Convert-Sorted-Array-to-Binary-Search-Tree/Solution.cpp new file mode 100644 index 0000000..331a525 --- /dev/null +++ b/Convert-Sorted-Array-to-Binary-Search-Tree/Solution.cpp @@ -0,0 +1,33 @@ +#include +using namespace std; + +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + +class Solution { +public: + TreeNode *sortedArrayToBST(vector &num) { + return sortedArrayToBST(num, 0, num.size()); + } + + TreeNode *sortedArrayToBST(vector &num, int start, int end) { + if (start + 1 >= end) { + return start + 1 == end ? new TreeNode(num[start]) : NULL; + } + + int mid = (start + end) / 2; + TreeNode *root = new TreeNode(num[mid]); + root->left = sortedArrayToBST(num, start, mid); + root->right = sortedArrayToBST(num, mid + 1, end); + + return root; + } +}; + +int main() { + return 0; +} diff --git a/Convert-Sorted-Array-to-Binary-Search-Tree/Solution.java b/Convert-Sorted-Array-to-Binary-Search-Tree/Solution.java new file mode 100644 index 0000000..7a60660 --- /dev/null +++ b/Convert-Sorted-Array-to-Binary-Search-Tree/Solution.java @@ -0,0 +1,26 @@ +public class Solution { + + public class TreeNode { + int val; + TreeNode left; + TreeNode right; + TreeNode(int x) { val = x; } + } + + public TreeNode sortedArrayToBST(int[] num) { + return this.sortedArrayToBST(num, 0, num.length); + } + + public TreeNode sortedArrayToBST(int[] num, int start, int end) { + if (start + 1 >= end) { + return start + 1 == end ? new TreeNode(num[start]) : null; + } + + int mid = (start + end) / 2; + TreeNode root = new TreeNode(num[mid]); + root.left = this.sortedArrayToBST(num, start, mid); + root.right = this.sortedArrayToBST(num, mid + 1, end); + + return root; + } +} diff --git a/Convert-Sorted-Array-to-Binary-Search-Tree/Solution.py b/Convert-Sorted-Array-to-Binary-Search-Tree/Solution.py new file mode 100644 index 0000000..15b149e --- /dev/null +++ b/Convert-Sorted-Array-to-Binary-Search-Tree/Solution.py @@ -0,0 +1,23 @@ +# Definition for a binary tree node +# class TreeNode: +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + +class Solution: + # @param num, a list of integers + # @return a tree node + def sortedArrayToBST(self, num): + return self.innerSortedArrayToBST(num, 0, len(num)) + + def innerSortedArrayToBST(self, num, start, end): + if start + 1 >= end: + return TreeNode(num[start]) if start + 1 == end else None + + mid = (start + end) / 2 + root = TreeNode(num[mid]) + root.left = self.innerSortedArrayToBST(num, start, mid) + root.right = self.innerSortedArrayToBST(num, mid + 1, end) + + return root