add: 220112

This commit is contained in:
Lam Haoyin 2022-01-12 21:15:41 +08:00
parent 86da1d183a
commit 1032f9464c
No known key found for this signature in database
GPG Key ID: 8C089CB1A2B7544F
2 changed files with 39 additions and 1 deletions

38
2201/220112.cpp Normal file
View File

@ -0,0 +1,38 @@
#include <iostream>
/**
* Definition for a binary tree node.
*/
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
explicit TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
~TreeNode() { delete this->left; delete this->right; }
};
class Solution {
public:
static TreeNode* insertIntoBST(TreeNode* root, int val) {
if (!root)
return new TreeNode(val);
if (val > root->val) {
if (root->right) {
insertIntoBST(root->right, val);
} else {
root->right = new TreeNode(val);
}
} else if (val < root->val) {
if (root->left) {
insertIntoBST(root->left, val);
} else {
root->left = new TreeNode(val);
}
} else {
return nullptr;
}
return root;
}
};

View File

@ -3,4 +3,4 @@ PROJECT(2201)
SET(CMAKE_CXX_STANDARD 23)
ADD_EXECUTABLE(2201 220112-CN.cpp)
ADD_EXECUTABLE(2201 220112.cpp)