[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);
	}
}

같은 알고리즘이 만약에 자바로 실현된다면 함수는 값 전달이기 때문에 전달을 인용할 수 없기 때문에head는 호출 과정에서 뒤로 가지 않고 그에 상응하는listnode와treenode를 저장해야 한다.

좋은 웹페이지 즐겨찾기