LeetCode:Convert Sorted List to Binary Search Tree
来源:互联网 发布:ntp服务器地址 端口 编辑:程序博客网 时间:2024/06/10 18:24
中序遍历思想,找到中位数构建根节点,然后左右链表递归构建左子树和右子树
class Solution {public: TreeNode *sortedListToBST(ListNode *head) { //递归方法实现,通过中位数构建树的根节点,左右子链表构建左子树和右子树 TreeNode *root=NULL; if(!head) return root; if(!head->next) { root=(TreeNode *)malloc(sizeof(TreeNode)); root->val=head->val; root->left=NULL; root->right=NULL; return root; } ListNode *p,*q,*pre;//pre指向中位数结点的前一个结点 p=head; q=head; pre=head; while(q&&q->next) { if(p!=head) pre=pre->next; p=p->next; q=q->next->next; } ListNode *mid;//mid为中位数结点 mid=p; pre->next=NULL; q=mid->next; root=(TreeNode *)malloc(sizeof(TreeNode)); root->val=mid->val; root->left=sortedListToBST(head); root->right=sortedListToBST(q); return root; }};
0 0
- 【LeetCode】Convert Sorted Array to Binary Search Tree && Convert Sorted List to Binary Search Tree
- LeetCode[Tree]: Convert Sorted List to Binary Search Tree
- [leetcode][list][dfs] Convert Sorted List to Binary Search Tree
- LeetCode: Convert Sorted List to Binary Search Tree
- [LeetCode]Convert Sorted List to Binary Search Tree
- LeetCode : Convert Sorted List to Binary Search Tree
- [Leetcode] Convert Sorted List to Binary Search Tree
- Leetcode: Convert Sorted List to Balanced Binary Search Tree
- [LeetCode] Convert Sorted List to Binary Search Tree
- leetcode 66: Convert Sorted List to Binary Search Tree
- leetcode Convert Sorted List to Binary Search Tree
- LeetCode Convert Sorted List to Binary Search Tree
- leetcode Convert Sorted List to Binary Search Tree
- LeetCode:Convert Sorted List to Binary Search Tree
- [LeetCode]Convert Sorted List to Binary Search Tree
- [Leetcode]Convert Sorted List to Binary Search Tree
- [leetcode]Convert Sorted List to Binary Search Tree
- Leetcode: Convert Sorted List to Binary Search Tree
- 学习IOS——你必须了解
- YT15-HDU-N皇后问题
- Extjs组件树形结构图
- 南阳33 蛇形填数
- 欢迎使用CSDN-markdown编辑器
- LeetCode:Convert Sorted List to Binary Search Tree
- 动态代理的简单示例
- 创建servlet应用
- 实现本地图片预览(ie11,chrome最新版,firefox最新版已测式通过)
- linux下的C语言编程(总结篇)
- Eclipse快捷键-方便查找
- Android双击事件的实现
- ecshop更改文章列表数量
- sublime text3 for mac 中文乱码