feat: leetcode Construct Binary Search Tree from Preorder Traversal solution (1008) (#1021)

Co-authored-by: David Leal <halfpacho@gmail.com>
This commit is contained in:
Sindhu Inti 2022-11-05 06:45:30 +05:30 committed by GitHub
parent 9ab1bc981b
commit a0f658311d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 41 additions and 1 deletions

View File

@ -90,9 +90,10 @@
| 938 | [Range Sum of BST](https://leetcode.com/problems/range-sum-of-bst/) | [C](./src/938.c) | Easy |
| 965 | [Univalued Binary Tree](https://leetcode.com/problems/univalued-binary-tree/) | [C](./src/965.c) | Easy |
| 977 | [Squares of a Sorted Array](https://leetcode.com/problems/squares-of-a-sorted-array/) | [C](./src/977.c) | Easy |
| 1008 | [Construct Binary Search Tree from Preorder Traversal](https://leetcode.com/problems/construct-binary-search-tree-from-preorder-traversal/description/) | [C](./src/1008.c) | Medium |
| 1019 | [Next Greater Node In Linked List](https://leetcode.com/problems/next-greater-node-in-linked-list/) | [C](./src/1019.c) | Medium |
| 1089 | [Duplicate Zeros](https://leetcode.com/problems/duplicate-zeros/) | [C](./src/1089.c) | Easy |
| 1184 | [Distance Between Bus Stops](https://leetcode.com/problems/distance-between-bus-stops/) | [C](./src/1184.c) | Easy |
| 1189 | [Maximum Number of Balloons](https://leetcode.com/problems/maximum-number-of-balloons/) | [C](./src/1189.c) | Easy |
| 1207 | [Unique Number of Occurrences](https://leetcode.com/problems/unique-number-of-occurrences/) | [C](./src/1207.c) | Easy |
| 2130 | [Maximum Twin Sum of a Linked List](https://leetcode.com/problems/maximum-twin-sum-of-a-linked-list/) | [C](./src/2130.c) | Medium |
| 2130 | [Maximum Twin Sum of a Linked List](https://leetcode.com/problems/maximum-twin-sum-of-a-linked-list/) | [C](./src/2130.c) | Medium |

39
leetcode/src/1008.c Normal file
View File

@ -0,0 +1,39 @@
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
struct TreeNode* bstFromPreorder(int* preorder, int preorderSize)
{
struct TreeNode* new;
int left_ptr;
new = malloc(sizeof(struct TreeNode));
new->val = preorder[0];
if (preorderSize == 1)
{
new->right = NULL;
new->left = NULL;
return new;
}
left_ptr = 1;
while ((left_ptr < preorderSize) && (preorder[left_ptr] < preorder[0]))
left_ptr++;
if (left_ptr == 1)
new->left = NULL;
else
new->left = bstFromPreorder(preorder + 1, left_ptr - 1);
if (left_ptr < preorderSize)
new->right =
bstFromPreorder(preorder + left_ptr, preorderSize - left_ptr);
else
new->right = NULL;
return new;
}