[toc]
题目
给定一个单链表,其中的元素按升序排序,将其转换为高度平衡的二叉搜索树。
本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。
示例:
1 2 3 4 5 6 7 8 9
| 给定的有序链表: [-10, -3, 0, 5, 9],
一个可能的答案是:[0, -3, 9, -10, null, 5], 它可以表示下面这个高度平衡二叉搜索树:
0 / \ -3 9 / / -10 5
|
思路
编码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
| package mrzhang.leecode;
public class Solution109function3 {
private ListNode head;
public static void main(String[] args) { int[] nums = {-10,-3,0,5,9, 13}; ListNode listNode = ListNode.getListNode(nums); Solution109function3 solution109 = new Solution109function3(); TreeNode root = solution109.sortedListToBST(listNode); TreeNode.prePrint(root); }
private TreeNode sortedListToBST(ListNode node) { int size = countListNodeSize(node); head = node; return convertListToBST(0, size - 1); }
private TreeNode convertListToBST(int left, int right) { if (right < left) return null; int mid = (right + left) / 2; TreeNode leftNode = convertListToBST(left, mid - 1); TreeNode result = new TreeNode(head.val); result.left = leftNode; head = head.next; result.right = convertListToBST(mid + 1, right); return result; }
private int countListNodeSize(ListNode head) { if (head == null) return 0; int sum = 0; ListNode p = head; while (p != null) { sum += 1; p = p.next; } return sum; }
}
|
更多详细代码见我的代码仓库
https://github.com/ZhangnLei/java-base/tree/master/src/main/java/mrzhang/leecode