zoukankan      html  css  js  c++  java
  • 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 binary tree
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        int ListLength(ListNode *head)
        {
            int len=0;
            while(head)
            {
                head=head->next;
                len++;
            }
            return len;
        }
        TreeNode *createBST(ListNode *head,int left,int right)
        {
            if(left>right)
                return NULL;
            int mid=(left+right)>>1;
            ListNode *cur=head;
            for(int i=left;i<mid;i++)
                cur=cur->next;
            TreeNode *leftTree=createBST(head,left,mid-1);
            TreeNode *rightTree=createBST(cur->next,mid+1,right);
            TreeNode *root=new TreeNode(cur->val);
            root->left=leftTree;
            root->right=rightTree;
            return root;
        }
        TreeNode *sortedListToBST(ListNode *head) {
            if(head==NULL)
                return NULL;
            int len;
            len=ListLength(head);
            return createBST(head,0,len-1);
        }
    };
  • 相关阅读:
    input表单元素的默认padding不一致问题
    【转】iOS25彩票 幸运转盘
    微分起源
    转载--微分几何为何必然兴起?
    前缀和?or差分序列?
    noip2014 小结
    2019艾瑞(北京)年度高峰会议-数能驱动新变量
    MSF初体验
    s实现指定时间自动跳转到某个页面
    css实现居中
  • 原文地址:https://www.cnblogs.com/awy-blog/p/3672318.html
Copyright © 2011-2022 走看看