class Solution {
public:
TreeNode* insertIntoBST(TreeNode* root, int val) {
if (root == nullptr) { //中
TreeNode* node = new TreeNode(val);
return node;
}
if (val > root->val) { //右
root->right = insertIntoBST(root->right, val);
}
if (val < root->val) { //左
root->left = insertIntoBST(root->left, val);
}
return root;
}
};
时间复杂度:O(h) h为树的高度
思路:因为是二叉搜索树,递归可以有方向。如何递归,首先确定递归的返回值,明显是树的根节点,然后确定递归的终止条件,很明显当遍历到空节点是终止递归,终止的同时,返回插入的节点值,最终确定单层的递归逻辑,因为底层返回的插入的值,上一层就要接住底层返回的值,所以用到left和right来接住底层的返回值,最终返回root即可。
迭代法:
class Solution {
public:
TreeNode* insertIntoBST(TreeNode* root, int val) {
TreeNode* node = new TreeNode(val);
if (root == nullptr) {
return node;
}
TreeNode* cur = root;
TreeNode* pre = root; //找到前一个节点,方便插入
while (cur != nullptr) { //找到要插入的节点
pre = cur;
if (cur->val > val) {
cur = cur->left;
} else {
cur = cur->right;
}
}
if (val > pre->val) { //判断查到节点左边还是右边
pre->right = node;
} else {
pre->left = node;
}
return root;
}
};