zoukankan      html  css  js  c++  java
  • 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.

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

    题目:将升序的链表,转化为BST(note:此BST要求是高度平衡,就是树种左右子树高度差不超过1)

    思路:

    def TreeNode* sortedListToBST(ListNode* head){
    
        按照slow/fast方式找到链表的中间节点mid,
    
        将升序链表在mid节点处切割成为两个链表head1,和head2
    
        将中间节点的值,new一个新的TreeNode节点:TreeNode *root = new TreeNode(head2->val)
    
        下面开始递归:
            root的左子树就是sortedListToBST(head1)
            root的右子树就是sortedListToBST(head2->next)
        return root
    }

    代码如下:

    /**
     * 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==nullptr){
                return nullptr;
            }else if(head->next==nullptr){
                return new TreeNode(head->val);
            }
    
            ListNode *slow,*fast,*prev;
            slow = fast = head;
            prev = nullptr;
            while(fast && fast->next){
                prev = slow;
                slow = slow->next;
                fast = fast->next->next;
            }
            prev->next = nullptr;
            //showList(head);
            //showList(slow);
            TreeNode *root = new TreeNode(slow->val);
            root->left = sortedListToBST(head);
            root->right = sortedListToBST(slow->next);
            return root;
        }
    };
  • 相关阅读:
    C# 数组 随机 排序
    安全防护之加盐慢哈希加密
    NLog的介绍使用
    xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance(xsi:schemaLocation详解)
    如何计算时间复杂度(转)
    ppp协议介绍(转)
    Netlink 介绍(译)
    TIME_WAIT状态的一些总结
    带头结点单链表的翻转(递归)
    压缩前端文件(html, css, js)
  • 原文地址:https://www.cnblogs.com/li-daphne/p/5606989.html
Copyright © 2011-2022 走看看