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

      

  • 相关阅读:
    shell 统计行数
    sqlldr errors
    sqlldr 远程数据库
    load Properties
    查看shell 版本
    linux中的网络通信指令
    给EditText的drawableRight属性的图片设置点击事件
    p2p网贷3种运营模式
    p2p网贷3种运营模式
    linux常用的压缩与解压缩命令
  • 原文地址:https://www.cnblogs.com/tyty-Somnuspoppy/p/12570809.html
Copyright © 2020-2023  润新知