zoukankan      html  css  js  c++  java
  • 109. Convert Sorted List to Binary Search Tree(根据有序链表构造平衡的二叉查找树)

    题意:根据有序链表构造平衡的二叉查找树。

    /**
     * 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:
        TreeNode* sortedListToBST(ListNode* head) {
            if(head == NULL) return NULL;
            if(head -> next == NULL) return new TreeNode(head -> val);
            ListNode *fast = head;
            ListNode *slow = head;
            ListNode *pre;
            while(fast && fast -> next){
                fast = fast -> next -> next;
                pre = slow;
                slow = slow -> next;
            }
            pre -> next = NULL;
            TreeNode *root = new TreeNode(slow -> val);
            root -> left = sortedListToBST(head);
            root -> right = sortedListToBST(slow -> next);
            return root;
        }
    };
    

      

  • 相关阅读:
    VSCode集成TypeScript编译
    http模拟登陆及发请求
    1​1​.​0​5​9​2​M​晶​振​与12M晶振
    单片机定时器2使用
    Altium Designer 小记
    sql-mysql
    java英文缩写
    Altium Design
    Tomcat使用
    jar/war/ear文件的区别
  • 原文地址:https://www.cnblogs.com/tyty-Somnuspoppy/p/12570809.html
Copyright © 2011-2022 走看看