二叉树-Convert Sorted List to Binary Search Tree

来源:互联网 发布:java 首字母小写 编辑:程序博客网 时间:2024/05/21 21:48

2014.8.18 update:
其实相当简单,就是找到链表的中间node然后左半边成为left node, 右半边成为right node

public class Solution {    public TreeNode sortedListToBST(ListNode head) {        if (head == null) {            return null;        }        ListNode tail = head;        while (tail.next != null) {            tail = tail.next;        }                return helper(head, tail);    }        TreeNode helper(ListNode head, ListNode tail) {        if (head == null || tail == null) {            return null;        }        if (head == tail) {            return new TreeNode(head.val);        }                ListNode fast = head;        ListNode slow = head;        ListNode preSlow = null;        while (fast.next != null && fast != tail) {            fast = fast.next;            if (fast.next == null || fast == tail) {                break;            } else {                fast = fast.next;            }            preSlow = slow;            slow = slow.next;        }                TreeNode returnNode = new TreeNode(slow.val);        returnNode.left = helper(head, preSlow);        returnNode.right = helper(slow.next, tail);        return returnNode;    }}

2013:
public class Solution {
    public TreeNodesortedListToBST(ListNode head) {
       // Start typing your Java solution below
       // DO NOT write main() function
       if (head == null) {
           returnnull;
       }
       ListNode cur = head;
       int count = 0;
       while (cur != null) {
          count++;
           cur =cur.next;
       }
       return helper(head, 0, count-1);
    }

    TreeNode helper(ListNodelistHead, int low, int high) {
       if (low > high) {
           returnnull;
       }
       int mid = low + (high-low)/2;
       TreeNode left = helper(listHead, low,mid-1);
       TreeNode parent = newTreeNode(listHead.val);
       if (listHead.next != null) {
           listHead.val = listHead.next.val;
           listHead.next = listHead.next.next;
       }
       TreeNode right = helper(listHead, mid+1,high);
       parent.left = left;
       parent.right = right;
       return parent;
    }
}
0 0
原创粉丝点击