瀏覽代碼

New problem done

master
Lachlan Jacob 5 年之前
父節點
當前提交
6a8daa4e82
共有 3 個檔案被更改,包括 73 行新增0 行删除
  1. 66
    0
      701/main.c
  2. 3
    0
      701/problem.txt
  3. 4
    0
      701/run.sh

+ 66
- 0
701/main.c 查看文件

@@ -0,0 +1,66 @@
#include <stdio.h>
#include <stdlib.h>

struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};

void insertIntoBSTRecursively(struct TreeNode*, int);

struct TreeNode* insertIntoBST(struct TreeNode* root, int val) {
insertIntoBSTRecursively(root, val);
return root;
}

void insertIntoBSTRecursively(struct TreeNode* tree, int val) {
if (val < tree->val) {
// Go left if possible
// else append a new TreeNode with this value
if (tree->left != NULL) {
insertIntoBSTRecursively(tree->left, val);
} else {
struct TreeNode *t = malloc(sizeof(struct TreeNode));
t->val = val;
t->left = NULL;
t->right = NULL;
tree->left = t;
}
} else {
// Go right if possible
// else append a new TreeNode with this value
if (tree->right != NULL) {
insertIntoBSTRecursively(tree->right, val);
} else {
struct TreeNode *t = malloc(sizeof(struct TreeNode));
t->val = val;
t->left = NULL;
t->right = NULL;
tree->right = t;
}
}
}

int main() {
struct TreeNode *t2 = malloc(sizeof(struct TreeNode));
t2->val = 2;
t2->left = NULL;
t2->right = NULL;
struct TreeNode *t3 = malloc(sizeof(struct TreeNode));
t3->val = 3;
t3->left = NULL;
t3->right = NULL;
struct TreeNode *t = malloc(sizeof(struct TreeNode));
t->val = 1;
t->left = t2;
t->right = t3;
printf("Expecting to add value `4` to tree...\n");
insertIntoBST(t, 4);
// Here check t contains 4 now.
if (t->right->right->val == 4) {
printf("Value `4` added to Tree!\n");
return 0;
}
return -1;
}

+ 3
- 0
701/problem.txt 查看文件

@@ -0,0 +1,3 @@
Given the root node of a binary search tree (BST) and a value to be inserted into the tree, insert the value into the BST. Return the root node of the BST after the insertion. It is guaranteed that the new value does not exist in the original BST.

Note that there may exist multiple valid ways for the insertion, as long as the tree remains a BST after insertion. You can return any of them.

+ 4
- 0
701/run.sh 查看文件

@@ -0,0 +1,4 @@
#!/bin/bash

gcc -o main main.c
./main

Loading…
取消
儲存