标签:指针 16px load png rgb 思路 双指针 搜索 img
思路:和108题类似,链表需要通过双指针寻找中间节点。
class Solution { public TreeNode sortedListToBST(ListNode head) { if (head == null) return null; if (head.next == null) return new TreeNode(head.val); ListNode fast = head, slow = head, pre = null; while (fast != null && fast.next != null) { pre = slow; fast = fast.next.next; slow = slow.next; } pre.next = null; TreeNode root = new TreeNode(slow.val); root.left = sortedListToBST(head); root.right = sortedListToBST(slow.next); return root; } }
标签:指针 16px load png rgb 思路 双指针 搜索 img
原文地址:https://www.cnblogs.com/HuangYJ/p/14190799.html