Leetcode 701. Insert into a Binary Search Tree
You are given the root of a binary search tree (BST) and an integer value. You need to insert this value into the BST such that the BST property is maintained. Return the root of the modified BST. It is guaranteed that the new value does not exist in the original BST.
Input: root = [4,2,7,1,3], val = 5
Output: [4,2,7,1,3,5]
null
, we have found the correct spot for insertion, so return a new node with the given value.#include <iostream>
// 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) {
// Base case: we've reached the end of the tree or the tree is empty
if (root == nullptr) {
return new TreeNode(val);
}
// If the value to be inserted is less than the root's value, insert it into the left subtree.
if (val < root->val) {
root->left = insertIntoBST(root->left, val);
}
// If the value to be inserted is greater than the root's value, insert it into the right subtree.
else {
root->right = insertIntoBST(root->right, val);
}
// Return the root as it is (might have new left or right child now).
return root;
}
};
h
is the height of the tree.n
is the number of nodes in the tree.h
is the height of the tree.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?