zoukankan      html  css  js  c++  java
  • lintcode-106-排序列表转换为二分查找树

    106-排序列表转换为二分查找树

    给出一个所有元素以升序排序的单链表,将它转换成一棵高度平衡的二分查找树

    样例

    标签

    递归 链表

    思路

    类似于二分查找,每次将链表二分,中间节点作为根节点,在建立左子树与右子树,递归即可

    code

    /**
     * Definition of ListNode
     * class ListNode {
     * public:
     *     int val;
     *     ListNode *next;
     *     ListNode(int val) {
     *         this->val = val;
     *         this->next = NULL;
     *     }
     * }
     * Definition of TreeNode:
     * class TreeNode {
     * public:
     *     int val;
     *     TreeNode *left, *right;
     *     TreeNode(int val) {
     *         this->val = val;
     *         this->left = this->right = NULL;
     *     }
     * }
     */
    class Solution {
    public:
        /**
         * @param head: The first node of linked list.
         * @return: a tree node
         */
        TreeNode *sortedListToBST(ListNode *head) {
            // write your code here
            TreeNode *root = NULL;
    
            if(head != NULL) {
                ListNode *left = NULL, *right = NULL;
                root = new TreeNode(dichotomyList(head, left, right));
                root->left = sortedListToBST(left);
                root->right = sortedListToBST(right);
            }
    
            return root;
        }
    
        int dichotomyList(ListNode *head, ListNode *&left, ListNode *&right) {
            if(head->next != NULL) {
                ListNode *fast = head, *slow = head, *temp = head;
                while(fast != NULL && fast->next != NULL) {
                    temp = slow;
                    slow = slow->next;
                    fast = fast->next->next;
                }
                temp->next = NULL;
            
                left = head;
                right = slow->next;
    
                return slow->val;
            }
            else {
                left = NULL;
                right = NULL;
                return head->val;
            }
        }
    };
    
  • 相关阅读:
    对象属性键值[key]属性问题
    理解 JavaScript 中的 for…of 循环
    vue初学篇----过滤器(filters)
    CSS变量
    SCSS !default默认变量
    vue 集成 NEditor 富文本
    如何在Github上面精准搜索开源项目?
    OSS介绍
    键盘各键对应的编码值(key code)
    网易云音乐歌单生成外链播放器
  • 原文地址:https://www.cnblogs.com/libaoquan/p/7171171.html
Copyright © 2011-2022 走看看