您的位置:首页 > 其它

【Leetcode】Two Problems: Convert Sorted Array/List to Binary Search Tree

2016-02-08 07:56 483 查看
First let's try easier one:

Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

The logic is very simple: Every time you find the middle element and put it as the root and recursively use the function for root.left
and root.right.

That's why we need a helper function to implement this.

/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
if(nums==null||nums.length==0)
return null;
return helper(nums,0,nums.length-1);
}
public TreeNode helper(int[] nums, int begin, int end){
if(begin > end) return null;//base case
int mid = (begin+end)/2;
TreeNode root = new TreeNode(nums[mid]);
root.left = helper(nums,begin, mid-1);
root.right = helper(nums, mid+1,end);
return root;
}
}


Then we advanced this problem as:

Given
a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.

Easiest way is to convert the unknown problem into a known problem.

Convert the LinkedList into Array:

/**
* Definition for singly-linked list.
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) { val = x; }
* }
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode sortedListToBST(ListNode head) {
if(head==null)
return null;
List<Integer> list = new ArrayList<Integer>();
while(head!=null){
list.add(head.val);
head = head.next;
}
int[] ret = new int[list.size()];
for (int i=0; i < ret.length; i++)
{
ret[i] = list.get(i).intValue();
}

return helper(ret,0,ret.length-1);
}

public TreeNode helper(int[] nums, int begin, int end){
if(begin>end)	return null;
int mid = (begin+end)/2;
TreeNode root = new TreeNode(nums[mid]);
root.left = helper(nums,begin, mid-1);
root.right = helper(nums,mid+1,end);
return root;
}
}


Do remember, never try to use iterative on tree

Must be some way of using recursive.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: