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

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

 

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

 

posted @ 2016-06-17 16:43  牧马人夏峥  阅读(95)  评论(0编辑  收藏  举报