LeetCode 刷题【109. 有序链表转换二叉搜索树】
109. 有序链表转换二叉搜索树
自己做
解:左旋
/*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode() {}* ListNode(int val) { this.val = val; }* ListNode(int val, ListNode next) { this.val = val; this.next = next; }* }*/
/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode() {}* TreeNode(int val) { this.val = val; }* TreeNode(int val, TreeNode left, TreeNode right) {* this.val = val;* this.left = left;* this.right = right;* }* }*/
class Solution {private int countTreeHeight(TreeNode root){if(root == null)return 0;int left = countTreeHeight(root.left);int right = countTreeHeight(root.right);return Integer.max(left, right) + 1;}public TreeNode sortedListToBST(ListNode head) {TreeNode root = null;TreeNode p = null;//插入根结点if(head != null){root = new TreeNode(head.val);p = root;head = head.next;}//后面边插入边调整while(head != null){p.right = new TreeNode(head.val);p = p.right;//插入后破坏平衡,检查有无破坏平衡//找到破坏平衡的最小子树【对应树的根结点为last_q,对应子树的父母为last】TreeNode last = null;TreeNode last_q = null;TreeNode q = root; while(q != null){int left = countTreeHeight(q.left);int right = countTreeHeight(q.right); //破坏了平衡的情况if(right - left >= 2){//找最小破坏平衡的子树while(right - left >= 2){last = last_q;last_q = q;q = q.right;left = countTreeHeight(q.left);right = countTreeHeight(q.right); }//左旋调整if(last_q == root){ //要调整根结点的情况last_q.right = q.left;q.left = last_q;root = q;}else{ //不用调整根结点的情况last_q.right = q.left;q.left = last_q; last.right = q;}//重置检查last = null;last_q = null;q = root; }//没有破坏平衡,继续往下找else{last = last_q;last_q = q;q = q.right;}}head = head.next;}return root;}
}
看题解
解:分治
官方题解:
class Solution {ListNode globalHead;public TreeNode sortedListToBST(ListNode head) {globalHead = head;int length = getLength(head);return buildTree(0, length - 1);}public int getLength(ListNode head) {int ret = 0;while (head != null) {++ret;head = head.next;}return ret;}public TreeNode buildTree(int left, int right) {if (left > right) {return null;}int mid = (left + right + 1) / 2;TreeNode root = new TreeNode();root.left = buildTree(left, mid - 1);root.val = globalHead.val;globalHead = globalHead.next;root.right = buildTree(mid + 1, right);return root;}
}
啊哈哈哈哈哈,原来根本不用左旋右旋这些