diff options
-rw-r--r-- | leetcode.c | 25 | ||||
-rw-r--r-- | leetcode.h | 6 |
2 files changed, 28 insertions, 3 deletions
@@ -53,6 +53,31 @@ struct TreeNode *treenode_create(int val) { return new; } +struct TreeNode *treenode_build(int *vals, int size) { + if (!size || vals[0] == -1) + return NULL; + struct TreeNode *root = treenode_create(vals[0]); + struct TreeNode **queue = + (struct TreeNode **)malloc(size * sizeof(struct TreeNode *)); + queue[0] = root; + int front = 0, rear = 1; + for (int i = 1; i < size; i++) { + struct TreeNode *curr = queue[front]; + if (vals[i] != -1) { + curr->left = treenode_create(vals[i]); + queue[rear++] = curr->left; + } + if (i + 1 < size && vals[i + 1] != -1) { + curr->right = treenode_create(vals[i + 1]); + queue[rear++] = curr->right; + } + i++; + front++; + } + free(queue); + return root; +} + void treenode_print(struct TreeNode *root) { if (!root) return; @@ -1,3 +1,4 @@ +#pragma once #include "lib/uthash/src/uthash.h" #include <assert.h> #include <ctype.h> @@ -9,13 +10,11 @@ #include <stdlib.h> #include <string.h> -#pragma once - #ifdef __cplusplus #include <bits/stdc++.h> using namespace std; -#define vvd(data) vector<vector<data>> +typedef vector<vector<int>> vvd; struct ListNode { int val; @@ -80,6 +79,7 @@ void listnode_print(struct ListNode *head); void listnode_free(struct ListNode *head); struct TreeNode *treenode_create(int val); +struct TreeNode *treenode_build(int *vals, int size); void treenode_print(struct TreeNode *root); void treenode_free(struct TreeNode *root); |