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;
    }
    }
  • 相关阅读:
    Python3高级基础(2)
    Python3面向对象基础
    Python3学习策略
    Python3基础之基本问题
    Python3基础之字典
    (转)修改IIS默认的localhost名称
    (转)IIS5.1的安装配置并发布ASP.NET网站
    (转)怎样查看局域网中自己的IP地址和其他电脑的IP地址?
    (转)sql中 in 、not in 、exists、not exists 用法和差别
    (转)union和union all的区别
  • 原文地址:https://www.cnblogs.com/zhuge134/p/10989336.html
Copyright © 2011-2022 走看看