Convert Sorted List to Binary Search Tree

来源:互联网 发布:张段固镇淘宝园 编辑:程序博客网 时间:2024/05/22 10:25

与Convert Sorted Array to Binary Search Tree类似,只不过是链表形式。

用快慢指针的方式找到中间节点,作为根节点。左边子链表作为参数传入,递归后得到二叉树的左子树

右边子链表作为参数传入,递归后得到右子树。

public TreeNode sortedListToBST(ListNode head) {        TreeNode tn = null;        if(head == null){            return null;        }        if(head.next == null){            tn = new TreeNode(head.val);            return tn;        }        ListNode slow = head;        ListNode fast = head;        ListNode pre = null;        while(fast!=null && fast.next!=null){            pre = slow;            slow = slow.next;            fast = fast.next.next;        }        tn = new TreeNode(slow.val);        pre.next = null;        slow = slow.next;        tn.left = sortedListToBST(head);        tn.right = sortedListToBST(slow);        return tn;    }


0 0