zoukankan      html  css  js  c++  java
  • Convert Sorted List to Binary Search Tree

    题目链接

    Convert Sorted List to Binary Search Tree - LeetCode

    注意点

    • 不要访问空结点
    • 题目要求的是平衡二叉搜索树(也就是AVL树)

    解法

    解法一:递归,二叉搜索树的中序遍历结果刚好是一个有序数组,有序数组中间的数字刚好是根节点,因此可以用二分的思想来做。不过这道题不像数组可以直接访问中间节点,要用快慢节点的方法。

    /**
     * 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:
        typedef TreeNode* Tnode;
        typedef ListNode* Lnode;
        TreeNode* sortedListToBST(ListNode* head) {
            if(!head) return NULL;
            return sortedListToBST(head,NULL);
        }
        TreeNode* sortedListToBST(Lnode head,Lnode tail) {
            if(head == tail) return NULL;
            Lnode slow = head, fast = head;
            while(fast != tail && fast->next != tail)
            {
                slow = slow->next;
                fast = fast->next->next;
            }
            Tnode n = new TreeNode(slow->val);
            n->left = sortedListToBST(head,slow);
            n->right = sortedListToBST(slow->next,tail);
            return n;
        }
    };
    
    

    小结

    • avl的子树高度差不超过1
  • 相关阅读:
    java基础之System类
    java基础之System类
    java基础之Random类
    java基础之Math类
    java基础之Math类
    java基础之Character类概述
    MySQL数据库
    JavaScript面向对象与原型
    PHP
    sass基础用法
  • 原文地址:https://www.cnblogs.com/multhree/p/10575666.html
Copyright © 2011-2022 走看看