zoukankan      html  css  js  c++  java
  • [leetcode] Convert Sorted List to Binary Search Tree

    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的很像,方法都一样,只是一个是数组的操作,一个是链表的操作。题外话,也是以后要注意的。开始认为这么做太费时间了,毕竟每次都要找中间节点,以为结果一定会TLE,所以没试。就看了别人写的,才发现这样可以。这题不算自己做出来的吧,以后不管怎样,都应该自己试试。

    题解:

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    /**
     * Definition for binary tree
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        int listlen(ListNode *head) {
            int len = 1;
            while(head->next) {
                len++;
                head = head->next;
            }
            return len;
        }
        void CreateBST(TreeNode *&root, ListNode *head, int l, int r) {
            ListNode *p = head;
            if(l<=r) {
                int mid = (l+r)/2;
                for(int i=l;i<mid;i++) {
                    p = p->next;
                }
                root = new TreeNode(p->val);
                CreateBST(root->left, head, l, mid-1);
                CreateBST(root->right, p->next, mid+1, r);
            }
        }
        TreeNode *sortedListToBST(ListNode *head) {
            TreeNode *root;
            if(head==NULL)
                return root;
            CreateBST(root, head, 0, listlen(head)-1);
            return root;
        }
    };
    View Code
  • 相关阅读:
    UVA11825 Hackers' Crackdown
    UVA 11346 Probability
    Codeforces 12 D Ball
    bzoj 4766: 文艺计算姬
    Codeforces 757 F Team Rocket Rises Again
    [HAOI2011] problem C
    Atcoder 3857 Median Sum
    bzoj4399 魔法少女LJJ
    bzoj2638 黑白染色
    bzoj4197 [Noi2015]寿司晚宴
  • 原文地址:https://www.cnblogs.com/jiasaidongqi/p/4182218.html
Copyright © 2011-2022 走看看