• 根据有序链表构造平衡的二叉查找树


    leetcode地址:

    https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/description/

    难度:中等

    描述:

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

    For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

    Example:

    Given the sorted linked list: [-10,-3,0,5,9],
    
    One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:
    
          0
         / 
       -3   9
       /   /
     -10  5


    解题思路:

    分为两步:

    1. 把链表转存到一个数组中,问题转化为:将一个有序数组转化为一个平衡二叉查找树。

    2. 取数组的中点为根节点,那么根节点的左子树是由左半边的数组生成的,右子树是由数组右半边生成的,分别对数组左半边和右半边进行递归调用

    代码:

    public class SortedListToBST {

    public TreeNode sortedListToBST(ListNode head) {
    int size = 0;
    ListNode p = head;
    while (p != null) {
    size++;
    p = p.next;
    }
    ListNode[] listNodes = new ListNode[size];
    p = head;
    int index = 0;
    while (p != null) {
    listNodes[index++] = p;
    p = p.next;
    }
    return sortedListToBST(listNodes, 0, listNodes.length);
    }

    public TreeNode sortedListToBST(ListNode[] listNodes, int start, int end) {
    if (start >= end) {
    return null;
    }
    int mid = (end + start) / 2;
    TreeNode root = new TreeNode(listNodes[mid].val);
    root.left = sortedListToBST(listNodes, start, mid);
    root.right = sortedListToBST(listNodes, mid + 1, end);
    return root;
    }
    }
  • 相关阅读:
    一个想法开发与业务,我们互相依赖
    vs2005中文包,和sqlserver2005中文开发版
    C中的指针
    建立一个新的web Site
    Visual Studio 2005 中的新增安全性功能
    htm和html的区别
    完美实现导航滑动功能
    如何避免AJAX的缓存问题
    两个常用的稳定的远端CDN jquery
    推荐一个CSS排错的网址
  • 原文地址:https://www.cnblogs.com/zhuge134/p/10989336.html
Copyright © 2020-2023  润新知