【leetcode】Convert Sorted Array/List to Binary Search Tree

Problem

这里写图片描述

Code

Solution1

/*
 * Dynamic programming,divide problem as two smaller 
 */
struct TreeNode* sortedArrayToBST(int* nums, int numsSize) {
    if(!numsSize)   return NULL;
    struct TreeNode *pNode = (struct TreeNode*)malloc(sizeof(struct TreeNode));
    pNode->val = nums[numsSize/2];
    pNode->left = sortedArrayToBST(nums,numsSize/2);
    pNode->right = sortedArrayToBST(&nums[numsSize/2+1],numsSize-numsSize/2-1);
    return pNode;
}

# Solution2

/*
 *Using ignored traversal
 */
struct TreeNode *buildTree(int *nums,int numsSize,int *index){
    if(!numsSize)   return NULL;
    struct TreeNode *pNode = (struct TreeNode *)malloc(sizeof(struct TreeNode));
    pNode->left = buildTree(nums,numsSize/2,index);
    pNode->val = nums[*index];
    ++(*index);
    pNode->right = buildTree(nums,numsSize-numsSize/2-1,index);
    return pNode;
}

struct TreeNode* sortedArrayToBST(int* nums, int numsSize) {
    int nIndex = 0;
    return buildTree(nums,numsSize,&nIndex);
}

Problem

这里写图片描述

Code

Solution1

/*
 *Transform the list to array
 */
 int countSize(struct ListNode *head){
     int nSize = 0;
     while(head!=NULL){
         head = head->next;
         ++nSize;
     }
     return nSize;
 }

 int *initArray(struct ListNode *head,int nSize){
     int *nums = (int*)malloc(sizeof(int)*nSize);
     int i = 0;
     while(i<nSize){
         nums[i++] = head->val;
         head = head->next;
     }
     return nums;
 }

struct TreeNode *buildTree(int *nums,int numsSize){
    if(!numsSize)   return NULL;
    struct TreeNode *pNode = (struct TreeNode*)malloc(sizeof(struct TreeNode));
    pNode->val = nums[numsSize/2];
    pNode->left = buildTree(nums,numsSize/2);
    pNode->right = buildTree(&nums[numsSize/2+1],numsSize-numsSize/2-1);
    return pNode;
}

struct TreeNode* sortedListToBST(struct ListNode* head) {
    int nSize = countSize(head);
    int *nums = initArray(head,nSize);
    return buildTree(nums,nSize);
}

Solution2

/*
 *Inorder traversal
 */
int countSize(struct ListNode *head){
    int nSize = 0;
    while(head!=NULL){
        ++nSize;
        head = head->next;
    }
    return nSize;
}

struct TreeNode *buildTree(struct ListNode **head,int numsSize){
    if(!numsSize)   return NULL;
    struct TreeNode *pNode = (struct TreeNode*)malloc(sizeof(struct TreeNode));
    pNode->left = buildTree(head,numsSize/2);
    pNode->val = (*head)->val;
    *head = (*head)->next;
    pNode->right = buildTree(head,numsSize-numsSize/2-1);
    return pNode;
}

struct TreeNode* sortedListToBST(struct ListNode* head) {
    return buildTree(&head,countSize(head));
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值