2023.7.12
比较简单,不多说直接看代码:
迭代法:
class Solution {
public:
TreeNode* insertIntoBST(TreeNode* root, int val) {
//树为空的情况
if(root==nullptr)
{
TreeNode* node = new TreeNode(val);
return node;
}
//需要一个pre节点指向父节点
TreeNode* cur = root;
TreeNode* pre = root;
//遍历,若cur值比val小,则cur往右走;反之
while(cur)
{
pre = cur;
if(cur->val < val) cur = cur->right;
else cur = cur->left;
}
//此时cur为空了,pre为cur父节点,最后判断一下大小执行插入操作
TreeNode* node = new TreeNode(val);
if(pre->val > val) pre->left = node;
else pre->right = node;
return root;
}
};
递归法:
class Solution {
public:
TreeNode* insertIntoBST(TreeNode* root, int val) {
if(root==nullptr)
{
TreeNode* node = new TreeNode(val);
return node;
}
if(root->val < val) root->right = insertIntoBST(root->right,val);
if(root->val > val) root->left = insertIntoBST(root->left,val);
return root;
}
};