Convert Sorted List to Binary Search Tree——将链表转换为平衡二叉搜索树 &&convert-sorted-array-to-binary-search-tree——将数列转换为bst
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.
为了满足平衡要求,容易想到提出中间节点作为树根,因为已排序,所以左右两侧天然满足BST的要求。
左右子串分别递归下去,上层根节点连接下层根节点即可完成。
递归找中点,然后断开前后两段链表,并继续找中点
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 /** 10 * Definition for binary tree 11 * struct TreeNode { 12 * int val; 13 * TreeNode *left; 14 * TreeNode *right; 15 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 16 * }; 17 */ 18 class Solution { 19 public: 20 TreeNode *sortedListToBST(ListNode *head) { 21 if(head==NULL) return NULL; 22 if(head->next==NULL) return new TreeNode(head->val); 23 ListNode *mid=findMid(head); 24 TreeNode *root=new TreeNode(mid->val); 25 root->left=sortedListToBST(head); 26 root->right=sortedListToBST(mid->next); 27 return root; 28 } 29 ListNode *findMid(ListNode *root){ 30 if(root==NULL) return NULL; 31 if(root->next==NULL) return root; 32 ListNode *fast,*slow,*pre; 33 fast=root; 34 slow=root; 35 while(fast!=NULL){ 36 fast=fast->next; 37 if(fast!=NULL){ 38 fast=fast->next; 39 pre=slow; 40 slow=slow->next; 41 } 42 } 43 pre->next=NULL; 44 return slow; 45 } 46 };
convert-sorted-array-to-binary-search-tree
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
1 /** 2 * Definition for binary tree 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 TreeNode *sortedArrayToBST(vector<int> &num) { 13 int n=num.size(); 14 if(n<1) return NULL; 15 16 return findMid(num,0,n-1); 17 } 18 TreeNode *findMid(vector<int> &num, int l,int r){ 19 if(l>r) return NULL; 20 int mid=(l+r+1)/2; 21 TreeNode *root=new TreeNode(num[mid]); 22 root->left=findMid(num,l,mid-1); 23 root->right=findMid(num,mid+1,r); 24 return root; 25 } 26 };
联系方式:emhhbmdfbGlhbmcxOTkxQDEyNi5jb20=
分类:
leetcode
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了