Convert Sorted List to Binary Search Tree
2015-06-01 15:47
155 查看
思路:
方法一:
类似上一题,用自顶向下的方法逐渐构造BST,每次找到midListNode,然后左边的顶点为其左子树,右边的顶点为其右子树。
但是由于链表不是可以随机访问的,每次必须遍历链表来找到中间的节点,时间复杂度比较高。
方法二:
方法一:
类似上一题,用自顶向下的方法逐渐构造BST,每次找到midListNode,然后左边的顶点为其左子树,右边的顶点为其右子树。
但是由于链表不是可以随机访问的,每次必须遍历链表来找到中间的节点,时间复杂度比较高。
/** * 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 { private: int listLength(ListNode *node) { int len = 0; while(node) { len++; node = node->next; } return len; } ListNode* buildNthListNode(ListNode *node, int len) { while(--len) { node = node->next; } return node; } TreeNode* buildBST(ListNode *head, int len) { if(len == 0) return nullptr; if(len == 1) return new TreeNode(head->val); TreeNode *root = new TreeNode(buildNthListNode(head, len/2+1)->val); root->left = buildBST(head, len/2); root->right = buildBST(buildNthListNode(head, len/2+2), (len-1)/2); return root; } public: TreeNode* sortedListToBST(ListNode* head) { return buildBST(head, listLength(head)); } };
方法二:
相关文章推荐
- Android深入浅出之Audio 第二部分 AudioFlinger分析
- STUN和TURN技术浅析
- 监听器接口适配器(方便适配器)
- 二值图像连通域标记
- 存储过程中执行动态Sql语句
- Linux安装配置php
- jni获取android端字符串转码为utf-8
- 用ImageBuilder定制自己的openwrt路由器
- 第五次作业
- [转]“Ceph浅析”系列之(—)—Ceph概况
- 工作5年了
- python mix-in
- 分页需要的
- 第十三周项目1——(3)
- BinTree::构造、析构、插入、删除
- 第十三周 项目一--动物 这样叫(3)有数据成员的抽象类
- C语言-----CGI程序
- unity插件
- 更改mysql默认引擎为Innodb 单个多个
- Java中的异常 Exception