zl程序教程

您现在的位置是:首页 >  其他

当前栏目

Leetcode 之Convert Sorted List to Binary Search Tree(55)

LeetCodeList to Tree search Binary sorted convert
2023-09-14 08:57:33 时间

和上题思路基本一致,不同的地方在于,链表不能随机访问中间元素。

 

int listLength(ListNode* node)
      {
          int n = 0;
          while (node)
          {
              n++;
              node = node->next;
          }
          return n;
      }
      ListNode* nth_node(ListNode* node, int n)
      {
          while (--n)node = node->next;
          return node;
      }
      TreeNode* sortedListToBST(ListNode* head)
      {
          sortedListToBST(head, listLength(head));
      }
      TreeNode* sortedListToBST(ListNode* head, int len)
      {
          if (len == 0)return nullptr;
          if (len == 1)return new TreeNode(head->val);

          TreeNode* root = new TreeNode(nth_node(head, len / 2 + 1)->val);
          root->left = sortedListToBST(head, len / 2);
          root->right = sortedListToBST(head, len / 2 + 2);

          return root;
      }
View Code