给定一个单链表,其中的元素按升序排序,将其转换为高度平衡的二叉搜索树。
本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。
示例:
给定的有序链表: [-10, -3, 0, 5, 9],
一个可能的答案是:[0, -3, 9, -10, null, 5], 它可以表示下面这个高度平衡二叉搜索树:
0
/ \
-3 9
/ /
-10 5
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/convert-sorted-list-to-binary-search-tree
1 import java.util.ArrayList; 2 import java.util.List; 3 4 public class ConvertSortedListToBST109 { 5 static class TreeNode { 6 int val; 7 TreeNode left; 8 TreeNode right; 9 TreeNode(int x) { 10 this.val = x; 11 } 12 } 13 static class ListNode { 14 int val; 15 ListNode next; 16 ListNode(int x) { 17 this.val = x; 18 } 19 } 20 public TreeNode sortedListToBST(ListNode head) { 21 List<Integer> list = new ArrayList<>(); 22 ListNode cur = head; 23 while(cur != null) { 24 list.add(cur.val); 25 cur = cur.next; 26 } 27 return toBST(list, 0, list.size() - 1); 28 } 29 30 public TreeNode toBST(List<Integer> list, int start, int end) { 31 if(start > end) { //相等的时候需要返回这一个节点,所以不能返回null 32 return null; 33 } 34 //或这当start == end时,直接返回节点 35 /* if(start == end) { 36 return new TreeNode(nums[start]); 37 }*/ 38 int mid = (start + end) / 2; 39 TreeNode root = new TreeNode(list.get(mid)); 40 root.left = toBST(list, start, mid - 1); 41 root.right = toBST(list, mid + 1, end); 42 return root; 43 } 44 45 //方法二:直接查找链表的中间节点 46 public TreeNode sortedListToBST2(ListNode head) { 47 if(head == null) { 48 return null; 49 } 50 if(head.next == null) { 51 return new TreeNode(head.val); 52 } 53 ListNode mid = searchMidNode(head); 54 55 TreeNode root = new TreeNode(mid.val); 56 root.left = sortedListToBST2(head); 57 root.right = sortedListToBST2(mid.next); 58 return root; 59 } 60 public ListNode searchMidNode(ListNode head) { 61 if(head == null) { 62 return null; 63 } 64 ListNode breakNode = null; 65 ListNode slow = head; 66 ListNode fast = head; 67 while(fast != null && fast.next != null) { 68 breakNode = slow; 69 slow = slow.next; 70 fast = fast.next.next; 71 } 72 if(breakNode != null){ //打断链表,将中间节点前一个节点置null,这样左子树就不会查找整个链表 73 breakNode.next = null; 74 } 75 return slow; 76 } 77 }
原文地址:https://www.cnblogs.com/xiyangchen/p/11144869.html
时间: 2024-10-08 01:44:07