• 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.

    转换成平衡二叉树,刚看到题目直接想到了中序,想了会没解决,于是一口气看了三部钢铁侠,“小辣椒”完美!好吧看完电影查了一下平衡二叉树的定义:

    在AVL树中任何节点的两个子树的高度最大差别为一,所以它也被称为高度平衡树

    把定义改成递归的,一棵树是平衡二叉树首先左右子树是平衡二叉树,并且左右子树高度差小于等于1。这样递归定义后就出来解决方案了。每次把链表二分,中间结点为根,左侧的作为左子树,右侧的作为右子树。递归结束条件是结点数小于等于0.代码:

     1     TreeNode *sortedListToBST(ListNode *head) {
     2         ListNode* p=head;
     3         int len=0;
     4         while(p){
     5             p=p->next;
     6             len++;
     7         }
     8         return sortedListToBST(head,len);
     9     }
    10     TreeNode *sortedListToBST(ListNode *head,int count){
    11         if(count<=0) return NULL;
    12         TreeNode *root = (TreeNode*)malloc(sizeof(TreeNode));
    13         ListNode *rootInList = getNode(head,count/2);
    14         root->val = rootInList->val;
    15         root->left = sortedListToBST(head,count/2);
    16         root->right = sortedListToBST(rootInList->next,count&1==1?count/2:(count/2-1));
    17         return root;
    18     }
    19     ListNode *getNode(ListNode *start,int count){
    20         if(start==NULL) return NULL;
    21         while(count-->0) start=start->next;
    22         return start;
    23     }

    16行需要注意的是当前链表个数在奇偶情况下右子树结点个数不同。

    时间复杂度是O(nlgn)了,感觉有点高。http://blog.csdn.net/taoqick/article/details/12774479,这位仁兄的方法O(n)解决,竟然方法就是之前没想出来的中序遍历,加了个二分才能搞定。

  • 相关阅读:
    python中不可变数据类型和可变数据类型
    悲观锁与乐观锁
    MySql的隔离级别和锁的关系
    关于content-type请求头的说明
    数据库事务的四大特性以及事务的隔离级别
    [Vue] : 路由
    [Vue] : 组件
    [Vue] : vue-resource 实现 get, post, jsonp请求
    [Vue] : 动画
    [Vue] : 自定义指令
  • 原文地址:https://www.cnblogs.com/mike442144/p/3427456.html
Copyright © 2020-2023  润新知