码迷,mamicode.com
首页 > 其他好文 > 详细

109. Convert Sorted List to Binary Search Tree

时间:2017-08-01 14:17:12      阅读:200      评论:0      收藏:0      [点我收藏+]

标签:div   bin   ==   efi   next   amp   tail   tree node   lin   

/**
 * 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

标签:div   bin   ==   efi   next   amp   tail   tree node   lin   

原文地址:http://www.cnblogs.com/apanda009/p/7267808.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!