Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
给一个按照递增顺序排列的链表。将该链表转化为平衡二叉树。面试
在这里须要注意的是,由于提供的数据结构为链表,因此咱们必须顺序遍历才能知道该链表的长度以及该链表的中间位置。在这里,咱们能够采用递归的形式,并且在递归中咱们经过双指针的方式找到其中的中间节点。并依次递归左子节点和右子节点。微信
public TreeNode sortedListToBST(ListNode head) { if(head==null) return null; return sortedListToBST(head, null); } public TreeNode sortedListToBST(ListNode head, ListNode tail){ if(head==tail) return null; ListNode fast = head; ListNode slow = head; while(fast!=tail && fast.next!=tail){ fast = fast.next.next; slow = slow.next; } TreeNode cHead = new TreeNode(slow.val); cHead.left = sortedListToBST(head, slow); cHead.right = sortedListToBST(slow.next, tail); return cHead; }
想要了解更多开发技术,面试教程以及互联网公司内推,欢迎关注个人微信公众号!将会不按期的发放福利哦~数据结构