leetcode Convert Sorted List to Binary Search Tree

265 篇文章 1 订阅
231 篇文章 0 订阅

Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

Example:

Given the sorted linked list: [-10,-3,0,5,9],

One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:

      0
     / \
   -3   9
   /   /
 -10  5

The problem is quite interesting when limiting memory to O(1), and time complexity to O(n). In that way, extra array is forbidden. So

When there is only one node A, mid = A, NULL<-mid->NULL

When there are two node A, A+1, mid = A, NULL<-mid->A+1

When there are three node A, A+1, A+2, mid = A+1, A<-A+1->A+2

....

After building the tree, the pointer moves to the end. The code is like: 

 

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
 public:
  TreeNode* BuildTree(ListNode*& head, int start, int end) {
      if (start > end) 
        return NULL;
      int mid = start + (end - start) / 2;
      
      TreeNode* lChild = BuildTree(head, start, mid - 1);
      TreeNode* parent = new TreeNode(head->val);
      parent->left = lChild;
      head = head->next;
      TreeNode* rChild = BuildTree(head, mid + 1, end);
      parent->right = rChild;
      return parent;
  }
  TreeNode *sortedListToBST(ListNode *head) {
    // Note: The Solution object is instantiated only once and is reused by each test case.
    ListNode* p = head;
    int len = 0; 
    while (p != NULL) {
        len++;
        p = p->next;
    }
    return BuildTree(head, 0, len-1);
  }
};


I once wrote the function like:

TreeNode* BuildTree(ListNode* head, int start, int end)

which got wrong answer. 

 

Python Version:

class Solution:
    def CountLen(self, head):
        sum = 0
        while (head):
            sum += 1
            head = head.next
        return sum

    def ConvertToBST(self, head, start, end):
        if (start > end or head == None):
            return None, head
        elif (start == end):
            root = TreeNode(head.val)
            head = head.next
            return root,head
        else:
            mid = start + ((end-start)//2)
            leftChild,head = self.ConvertToBST(head, start, mid-1)
            root = TreeNode(head.val)
            head = head.next
            rightChild,head = self.ConvertToBST(head, mid+1, end)
            root.left = leftChild
            root.right = rightChild
            return root,head

    def sortedListToBST(self, head):
        lens = self.CountLen(head)
        root, head = self.ConvertToBST(head, 0, lens-1)
        return root

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值