Problem
Code
Solution1
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
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
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));
}