【LeetCode】Convert Sorted List to Binary Search Tree

HIT_微笑前進發表於2015-03-28

題目:Convert Sorted List to Binary Search Tree


<span style="font-size:18px;">/**LeetCode convert link-list to Binary Search Tree
 *題意:給定一個按照升序排列的連結串列,要求將其轉化為一個高度平衡的二查搜尋樹
 *思路:因為連結串列是升序排列的,所以轉化為二叉搜尋樹是簡單的,但是要求是平衡的,即左右子數的高度 差在1之內
 *可以取中間的點為根節點,保證兩邊數量是一樣的,這樣遞迴下來就能得到平衡的二叉樹
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; next = null; }
 * }
 */
/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
package javaTrain;

public class Train19 {
	public TreeNode sortedListToBST(ListNode head) {
		if(head == null) return null;
        ListNode pre = head;		//用於找到中間的節點
        ListNode last = head;
        TreeNode root;;
		if(head.next == null){
			root = new TreeNode(head.val);
			root.left = null;
			root.right = null;
			return root;
		}
        while(pre != null && pre.next != null){	//找到中間節點
        	pre = pre.next.next;
        	last = last.next;
        } 
        root = new TreeNode(last.val);
        ListNode newHead = last.next;
        last.next = null;
        root.left = sortedListToBST(head);
        root.right = sortedListToBST(newHead);
        return root;
    }
}
</span>


相關文章