aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--leetcode.c25
-rw-r--r--leetcode.h6
2 files changed, 28 insertions, 3 deletions
diff --git a/leetcode.c b/leetcode.c
index 0a5925d..b6fe769 100644
--- a/leetcode.c
+++ b/leetcode.c
@@ -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;
diff --git a/leetcode.h b/leetcode.h
index cc01748..c68a56a 100644
--- a/leetcode.h
+++ b/leetcode.h
@@ -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);