• 109. Convert Sorted List to Binary Search Tree


    问题描述:

    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

    解题思路:

    将一个排好序的链表变成一个平衡的二叉搜索树,我们可以采用分治法来做这道题目

    使用快慢指针找到这个链表的中点,将链表分为3部分:左链表,中点,右链表。

    记得做链表的最后一个节点要与中点断开。

    中点建立为新的根节点,然后对左子链表和右子链表进行构造树。

    代码:

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        TreeNode* sortedListToBST(ListNode* head) {
            if(!head) return NULL;
            if(!head->next) return new TreeNode(head->val);
            
            
            //splict into 2 list
            ListNode *fast = head, *slow = head, *pre = NULL;
            while(fast && fast->next){
                fast = fast->next->next;
                pre = slow;
                slow = slow->next;
            }
            if(pre) pre->next = NULL;
            TreeNode* root = new TreeNode(slow->val);
            if(head != slow)root->left = sortedListToBST(head);
            root->right = sortedListToBST(slow->next);
            return root;
        }
    };
  • 相关阅读:
    跳出语句 break continue
    循环语句 for循环、while循环、do while循环
    选择语句
    判断语句
    方法入门
    ++运算与--运算
    js面向对象的几种方式----工厂模式、构造函数模式、原型模式
    JavaScript This 的六道坎
    前端必备,十大热门的 JavaScript 框架和库
    localStorage、sessionStorage详解,以及storage事件使用
  • 原文地址:https://www.cnblogs.com/yaoyudadudu/p/9302760.html
Copyright © 2020-2023  润新知