zoukankan      html  css  js  c++  java
  • leetcode

    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 binary tree
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    struct ListNode
    {
    	int val;
    	ListNode *next;
    	ListNode(int x) : val(x), next(NULL) {}
    };
    struct TreeNode
    {
    	int val;
    	TreeNode *left;
    	TreeNode *right;
    	TreeNode(int x) :val(x), left(NULL), right(NULL) {}
    };
    class Solution {
    public:
        TreeNode *sortedListToBST(ListNode *head) {
    		int n = 0;
    		ListNode *p = head;
    		while(p != NULL)
    		{
    			p = p->next;
    			n++;
    		}
    		return ListToBST(head,0,n-1);
        }
    private:
    	TreeNode *ListToBST(ListNode *&head,int start, int end)
    	{
    		if(start > end) return NULL;
    		int mid = (start + end) / 2;
    		TreeNode *left = ListToBST(head,start,mid - 1);
    		TreeNode *node = new TreeNode(head->val);
    		node->left = left;
    		head = head->next;
    		node->right = ListToBST(head,mid + 1,end);
    		return node;
    	}
    };


    版权声明:本文博客原创文章,博客,未经同意,不得转载。

  • 相关阅读:
    ZZ: kvm qemu kqemu qemu-kvm libvirt
    ZZ:爬虫
    Mac下安装及配置Appium环境
    badboy使用手册
    如何正确做 Web端压力测试?
    关于web页面性能测量指标与建议
    Pycharm的使用一
    如何下载安装Python
    apache jmeter下载与安装
    但行其事,不问前程
  • 原文地址:https://www.cnblogs.com/blfshiye/p/4749666.html
Copyright © 2011-2022 走看看