[LeetCode-24]Convert Sorted List to Binary Search Tree

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

It is similar with "Convert Sorted Array to Binary Search Tree". But the difference here is we have no way to random access item in O(1).

If we build BST from array, we can build it from top to bottom, like
1. choose the middle one as root,
2. build left sub BST
3. build right sub BST
4. do this recursively.

But for linked list, we can't do that because Top-To-Bottom are heavily relied on the index operation.
There is a smart solution to provide an Bottom-TO-Top as an alternative way, http://leetcode.com/2010/11/convert-sorted-list-to-balanced-binary.html

With this, we can insert nodes following the list’s order. So, we no longer need to find the middle element, as we are able to traverse the list while inserting nodes to the tree.


c++

TreeNode *sortedListToBST(ListNode *head) {
        int len = 0;
        ListNode *p = head;
        while(p){
            len++;
            p = p->next;
        }
        return buildBST(head, 0, len-1);
    }
    TreeNode *buildBST(ListNode *& head, int start, int end){
        if(start > end) return NULL;
        int mid = (start + end)/2;
        TreeNode *leftNode = buildBST(head, start, mid-1);
        TreeNode *parent = new TreeNode(head->val);
        parent->left = leftNode;
        head = head->next;
        parent->right = buildBST(head, mid+1, end);
        
        return parent;
    }

java

public class Solution {
    public class Element{
		ListNode n;
		TreeNode t;
		public Element(ListNode listNode, TreeNode treeNode){
			this.n = listNode;
			this.t = treeNode;
		}
	}
	public TreeNode sortedListToBST(ListNode head) {
        int len = 0;
        ListNode pNode = head;
        while(pNode!=null){
        	len++;	
        	pNode = pNode.next;
        }
        return buildBST(head, 0, len-1).t;
    }
	public Element buildBST(ListNode head, int start, int end){
		if(start>end) return new Element(head, null);
		int middle = (start+end)/2;
		Element left = buildBST(head, start, middle-1);
		head = left.n;
		TreeNode rootNode = new TreeNode(head.val);
		rootNode.left = left.t;
		head = head.next;
		Element right = buildBST(head, middle+1, end);
		rootNode.right = right.t;
		return new Element(right.n, rootNode);
	}
}

同样的算法如果用java实现,因为函数是值传递,无法引用传递,head在调用过程不会往后走,另需要element存储相应的listnode和treenode.



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值