Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
Divide and Conquer
publicTreeNodesortedListToBST(ListNode head) {if (head ==null){returnnull; }returnBSTHelper(head,null);}publicTreeNodeBSTHelper(ListNode head,ListNode tail) {if (head == tail){returnnull; }// let slow goes to middle pointListNode slow = head, fast = head;while(fast.next!= tail &&fast.next.next!= tail){ slow =slow.next; fast =fast.next.next; }TreeNode left =BSTHelper(head, slow);TreeNode right =BSTHelper(slow.next, tail);TreeNode root =newTreeNode(slow.val);root.left= left;root.right= right;return root;}
426 Convert BST to double linked list
Convert a BST to a sorted circular doubly-linked list in-place. Think of the left and right pointers as synonymous to the previous and next pointers in a doubly-linked list.並且首尾相連
privateNode pre;publicNodetreeToDoublyList(Node root) {if(root ==null) returnnull;Node dummy =newNode(0); pre = dummy;helper(root);// now the "pre" is the tail node// connect head and tailpre.right=dummy.right;dummy.right.left= pre;returndummy.right;}privatevoidhelper(Node node){if(node ==null) return;helper(node.left);pre.right= node; // 同時將dummy.right 指向 head nodenode.left= pre; pre = node; // 這裏dummy 不跟著變化helper(node.right);}