109. Convert Sorted List to Binary Search Tree
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了109. Convert Sorted List to Binary Search Tree相关的知识,希望对你有一定的参考价值。
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public TreeNode sortedListToBST(ListNode head) { if (head == null) return null; return helper(head, null); } private TreeNode helper(ListNode head, ListNode tail) { if (head == tail) return null; ListNode fast = head; ListNode slow = head; while (fast != tail && fast.next != tail) { fast = fast.next.next; slow = slow.next; } TreeNode cur = new TreeNode(slow.val); cur.left = helper(head, slow); cur.right = helper(slow.next, tail); return cur; } }
考察后序建树和递归出口的设置:
return helper(head, null);
if (head == tail) return null;
虽然arraylist 是
return helper(nums, 0, nums.length - 1);
if (start > end) return null,
if (start == end) {
T t = new T(nums[end]);
root.left = null;
root.right = null;
return root;
以上是关于109. Convert Sorted List to Binary Search Tree的主要内容,如果未能解决你的问题,请参考以下文章