题目:
题解
题解:二叉搜索树的左子树小于跟节点,右子树大于跟节点,并且左边子树和右边子树所有的结点都满足这个规律,所以用快慢指针找中间的跟节点,初始化数让中间的节点为跟结点,依次分为左子树和右子树,为两个树,再找这个两个树的中点,依次递归找每次左子树的头从head开始到pre结束。右子树从slow.next开始到结束。最后返回树。
代码
public TreeNode sortedListToBST(ListNode head) {
if (head == null) {
return null;
}
if (head.next == null) {
return new TreeNode(head.val);
}
//经典的快慢指针找中点
ListNode fast = head;
ListNode slow = head;
ListNode pre = null;
while (fast != null && fast.next != null) {
pre = slow;
slow = slow.next;
fast = fast.next.next;
}
//中间结尾
pre.next = null;
TreeNode node = new TreeNode(slow.val);
node.left = sortedListToBST(head);
node.right = sortedListToBST(slow.next);
return node;
}
备注
本文正在参与「掘金 2021 春招闯关活动」, 点击查看。