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

本文介绍如何将有序数组及单链表转换为高度平衡的二叉搜索树(BST)。通过递归地选取中间元素作为根节点,并递归构造左右子树的方法实现。同时提供了一种将链表转化为数组的过渡方案。

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值