[leet code] Convert Sorted List to Binary Search Tree

本文介绍如何将一个升序排列的单链表转换为高度平衡的二叉搜索树(BST)。通过将链表转化为有序数组,并采用递归方式从中点构造树节点,确保左右子树的高度差不超过1。

Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST

=================

Analysis:

Rules of height balanced BST:

1. all node values in left subtree less than value of current node

2. all node values in right subtree less than value of current node

3. heigh difference no more than 1

In this problem, we are given a sorted linked list, which can be transformed to a sorted array list.  Then the problem can be simplified to construct a height balanced BST from sorted numbers.

Obviously, we can use recursive approach.  Each recursive call construct one tree node.  Therefore, in each recursive call:

1. set value of current node as the middle element of the given array (according to rule1&2, value of current node should be value of the middle element of the given array)

2. set left subtree by recursive call with left->middle-1 array elements

3. set right subtree by recursive call with middle+1->right array elements

exist: left>right

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; next = null; }
 * }
 */
/**
 * Definition for binary tree
 * 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;
        
        ArrayList<Integer> listNode = new ArrayList<Integer>();
        while(head != null){
            listNode.add(head.val);
            head = head.next;
        }
        int left = 0;
        int right= listNode.size()-1;
        return helper(listNode, left, right);
    }
    
    public TreeNode helper(ArrayList<Integer> listNode, int left, int right){
        if(left>right) return null;
        
        TreeNode node = new TreeNode(0);
        int mid = (left+right)/2;
        node.val = listNode.get(mid);
        node.left = helper(listNode, left, mid-1);
        node.right = helper(listNode, mid+1, right);            
        return node;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值