Skip to content

Commit

Permalink
add solutions for Convert-Sorted-Array-to-Binary-Search-Tree
Browse files Browse the repository at this point in the history
  • Loading branch information
xcv58 committed Jan 25, 2015
1 parent dcebf12 commit 3abdadd
Show file tree
Hide file tree
Showing 3 changed files with 82 additions and 0 deletions.
33 changes: 33 additions & 0 deletions Convert-Sorted-Array-to-Binary-Search-Tree/Solution.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
#include <vector>
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<int> &num) {
return sortedArrayToBST(num, 0, num.size());
}

TreeNode *sortedArrayToBST(vector<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 = sortedArrayToBST(num, start, mid);
root->right = sortedArrayToBST(num, mid + 1, end);

return root;
}
};

int main() {
return 0;
}
26 changes: 26 additions & 0 deletions Convert-Sorted-Array-to-Binary-Search-Tree/Solution.java
Original file line number Diff line number Diff line change
@@ -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;
}
}
23 changes: 23 additions & 0 deletions Convert-Sorted-Array-to-Binary-Search-Tree/Solution.py
Original file line number Diff line number Diff line change
@@ -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

0 comments on commit 3abdadd

Please sign in to comment.