This commit is contained in:
Sainnhe Park 2023-02-01 10:57:38 +08:00
parent 5190b92cbb
commit 8c694f2996
3 changed files with 38 additions and 0 deletions

View File

@ -0,0 +1,11 @@
#ifndef S0701_INSERT_INTO_A_BINARY_SEARCH_TREE_HPP
#define S0701_INSERT_INTO_A_BINARY_SEARCH_TREE_HPP
#include "structures.hpp"
class S0701 {
public:
TreeNode* insertIntoBST(TreeNode* root, int val);
};
#endif

View File

@ -1,3 +1,4 @@
# 二叉搜索树
- [s0235](https://leetcode.cn/problems/lowest-common-ancestor-of-a-binary-search-tree/description/): 找两个指定节点的最近公共祖先。思路很简单,只要出现分岔(即一个在当前节点的左边,一个在当前节点的右边),那么这个分岔点就是最近公共祖先。
- [s0701](https://leetcode.cn/problems/insert-into-a-binary-search-tree/description/): 插入节点。一层一层往下找,直到发现找不到了就在这个地方插入。

View File

@ -0,0 +1,26 @@
#include "s0701_insert_into_a_binary_search_tree.hpp"
TreeNode* S0701::insertIntoBST(TreeNode* root, int val) {
TreeNode *cur = root;
if (root == nullptr) {
return new TreeNode(val);
}
while (true) {
if (val < cur->val) {
if (cur->left == nullptr) {
cur->left = new TreeNode(val);
break;
} else {
cur = cur->left;
}
} else {
if (cur->right == nullptr) {
cur->right = new TreeNode(val);
break;
} else {
cur = cur->right;
}
}
}
return root;
}