zoukankan      html  css  js  c++  java
  • 根据有序链表构造平衡的二叉查找树

    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;
    }
    }
  • 相关阅读:
    python调用c/c++库函数方法小结(c++和python的整合)
    一个机器学习的好网站
    Notepad++支持列选择模式
    awk的效率和python split 效率对比
    python 中的反射,装饰器,with语句
    hierarchy 在大数据上聚类的利弊
    shell 某个日期前的某一天(待补充)
    通过 cgi 运行 python 在lighttp上
    (译)Node.js的全局变量
    (译)Node.js的模块-exports和module.exports
  • 原文地址:https://www.cnblogs.com/zhuge134/p/10989336.html
Copyright © 2011-2022 走看看