• 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.

    题目解析:

    已知一个单链表,当中元素都是升序排列的,如今将链表转成平衡二叉树。

    方法一:

    我们用一个数组存储链表中元素,这样就能够利用下标訪问元素。之后依据二分查找法找树的每个节点就可以,代码例如以下:

    /**
     * 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:
    vector<int> list;
        TreeNode* makeTree(int start,int end)
        {
            if(start>end)
            return NULL;
            int mid=(start+end)/2;
            TreeNode* root=new TreeNode(list[mid]);
            TreeNode* left=makeTree(start,mid-1);
            TreeNode* right=makeTree(mid+1,end);
            root->left=left;
            root->right=right;
            return root;
        }
        TreeNode* sortedListToBST(ListNode* head) {
            if(head==NULL) return NULL;
            ListNode* p=head;
            while(p)
            {
                list.push_back(p->val);
                p=p->next;
            }
             return makeTree(0,list.size()-1);
        }
    };

    方法二

    不用额外开辟空间,记录链表的长度以及表头就可以,代码例如以下:
    class Solution {
    public:
        int length(ListNode* head)
        {
            int len=0;
            ListNode* p=head;
            while(p)
            {
                len++;
                p=p->next;
            }
            return len;
        }
        TreeNode* makeTree(ListNode* head,int start,int end)
        {
            if(start>end)
            return NULL;
            int mid=(start+end)/2;
            ListNode* p=head;
            for(int i=start;i<mid;i++)
            {
                p=p->next;
            }
            TreeNode* root=new TreeNode(p->val);
            TreeNode* left=makeTree(head,start,mid-1);
            TreeNode* right=makeTree(p->next,mid+1,end);
            root->left=left;
            root->right=right;
            return root;
        }
        TreeNode* sortedListToBST(ListNode* head) {
            if(head==NULL) return NULL;
            ListNode* p=head;
           int len=length(p);
             return makeTree(p,0,len-1);
        }
    };


  • 相关阅读:
    Volatile关键字
    ThreadPoolExecutor线程池基本原理及使用
    HashMap线程不安全源码解析(1.7 + 1.8)
    SpringBoot+ajax+formData实现图片上传和回显
    BloomFilter
    POST和GET
    快手电话面试
    Apache SSI 远程命令执行漏洞
    SYSTEM--服务器提权
    封神台靶场练习(2)
  • 原文地址:https://www.cnblogs.com/gavanwanggw/p/7018901.html
Copyright © 2020-2023  润新知