/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode *insertIntoBST(TreeNode *root, int val) {
TreeNode *newNode = new TreeNode(val);
if (root == nullptr) {
return newNode;
}
TreeNode *node = root;
while (node != nullptr) {
if (node->val < val) {
if (node->right == nullptr) {
node->right = newNode;
break;
}
node = node->right;
} else {
if (node->left == nullptr) {
node->left = newNode;
break;
}
node = node->left;
}
}
return root;
}
};
n is the number of nodes in the BST.
My Solution Solution 1: DFS (recursion) The Key Idea for Solving This Coding Question C++ Code /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right;
Jun 6, 2025MyCircularQueueO(k)
Apr 20, 2025O(m)
Mar 4, 2025O(n)n is the length of nums.
Feb 19, 2025or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up