本文主要是介绍Java | Leetcode Java题解之第109题有序链表转换二叉搜索树,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目:
题解:
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;}
}
这篇关于Java | Leetcode Java题解之第109题有序链表转换二叉搜索树的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!