在 C++ 中将排序链表转换成二叉搜索树


假设我们有一个单链表,其中元素按升序排列,我们必须将其转换成高度平衡的 BST。因此,如果链表为 [-10, -3, 0, 5, 9],则可能的树将如下图所示 −

为解决此问题,我们将遵循以下步骤 −

  • 如果链表为空,则返回 null

  • 定义名为 sortedListToBST() 的递归方法,这将采取链表开始节点

  • x := 从链表 a 中 mid 节点的上一个节点的地址

  • mid := 确切的 mid 节点

  • 创建一个新节点,其值取自 mid 的值

  • nextStart := mid 节点的下一个

  • 将 mid 的下一个设为 null

  • 节点的右侧 := sortedListToBST(nextStart)

  • 如果 x 为非 null,则 x 的下一个 = null,并且节点的左侧 := sortedListToBST(a)

  • 返回节点

示例 (C++)

让我们看看下面的实现以获得更好的理解 −

 实时演示

#include <bits/stdc++.h>
using namespace std;
class ListNode{
   public:
   int val;
   ListNode *next;
   ListNode(int data){
      val = data;
      next = NULL;
   }
};
ListNode *make_list(vector<int> v){
   ListNode *head = new ListNode(v[0]);
   for(int i = 1; i<v.size(); i++){
      ListNode *ptr = head;
      while(ptr->next != NULL){
         ptr = ptr->next;
      }
      ptr->next = new ListNode(v[i]);
   }
   return head;
}
class TreeNode{
   public:
   int val;
   TreeNode *left, *right;
   TreeNode(int data){
      val = data;
      left = right = NULL;
   }
};
void inord(TreeNode *root){
   if(root != NULL){
      inord(root->left);
      cout << root->val << " ";
      inord(root->right);
   }
}
class Solution {
   public:
   pair <ListNode*, ListNode*> getMid(ListNode* a){
      ListNode* prev = NULL;
      ListNode* fast = a;
      ListNode* slow = a;
      while(fast && fast->next){
         fast = fast->next->next;
         prev = slow;
         slow = slow->next;
      }
      return {prev, slow};
   }
   TreeNode* sortedListToBST(ListNode* a) {
      if(!a)return NULL;
      pair<ListNode*, ListNode*> x = getMid(a);
      ListNode* mid = x.second;
      TreeNode* Node = new TreeNode(mid->val);
      ListNode* nextStart = mid->next;
      mid->next = NULL;
      Node->right = sortedListToBST(nextStart);
      if(x.first){
         x.first->next = NULL;
         Node->left = sortedListToBST(a);
      }
      return Node;
   }
};
main(){
   vector<int> v = {-10,-3,0,5,9};
   ListNode *head = make_list(v);
   Solution ob;
   inord(ob.sortedListToBST(head));
}

输入

[-10,-3,0,5,9]

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

输出

-10 -3 0 5 9

更新于:2020 年 4 月 29 日

140 次浏览

开启您的 职业生涯

通过完成此课程获得认证

开始学习
广告