From 8c694f29966c74e548b70ad48c502ab2f4631923 Mon Sep 17 00:00:00 2001 From: Sainnhe Park Date: Wed, 1 Feb 2023 10:57:38 +0800 Subject: [PATCH] s0701 --- ...s0701_insert_into_a_binary_search_tree.hpp | 11 ++++++++ notes/src/bstree.md | 1 + ...s0701_insert_into_a_binary_search_tree.cpp | 26 +++++++++++++++++++ 3 files changed, 38 insertions(+) create mode 100644 include/s0701_insert_into_a_binary_search_tree.hpp create mode 100644 src/s0701_insert_into_a_binary_search_tree.cpp diff --git a/include/s0701_insert_into_a_binary_search_tree.hpp b/include/s0701_insert_into_a_binary_search_tree.hpp new file mode 100644 index 0000000..a503062 --- /dev/null +++ b/include/s0701_insert_into_a_binary_search_tree.hpp @@ -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 diff --git a/notes/src/bstree.md b/notes/src/bstree.md index 1bb9703..d4e75e3 100644 --- a/notes/src/bstree.md +++ b/notes/src/bstree.md @@ -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/): 插入节点。一层一层往下找,直到发现找不到了就在这个地方插入。 diff --git a/src/s0701_insert_into_a_binary_search_tree.cpp b/src/s0701_insert_into_a_binary_search_tree.cpp new file mode 100644 index 0000000..e90adea --- /dev/null +++ b/src/s0701_insert_into_a_binary_search_tree.cpp @@ -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; +}