• 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);
        }
    };


  • 相关阅读:
    Python split()方法分割字符串
    Python创建线程
    Python find()方法
    webpack中‘vant’全局引入和按需引入【vue-cli】
    webpack中‘mint-ui’全局引入和按需引入【vue-cli】
    nginx中 处理post方式打开页面的报错405
    nginx中 vue路由去掉#后的配置问题
    webpack中 VUE使用搜狐ip库查询设备ip地址
    webpack中 VUE使用百度地图获取地理位置
    VUE动态设置网页head中的title
  • 原文地址:https://www.cnblogs.com/gavanwanggw/p/7018901.html
Copyright © 2020-2023  润新知