方法一:迭代
class Solution
{
public:
TreeNode* insertIntoBST(TreeNode* root, int val)
{
TreeNode* parent = root;
TreeNode* child = root;
if (root == nullptr)
{
root = new TreeNode{ val };
return root;
}
while (child != nullptr)
{
parent = child;
if (val < child->val)
{
child = child->left;
}
else if (val > child->val)
{
child = child->right;
}
else
{
return root;
}
}
child = new TreeNode{ val };
if (val > parent->val)
{
parent->right = child;
}
else
{
parent->left = child;
}
return root;
}
};
方法二:递归
class Solution
{
public:
TreeNode* insertIntoBST(TreeNode* root, int val)
{
if (root == nullptr)
{
root = new TreeNode{ val };
}
else if (val < root->val)
{
root->left = insertIntoBST(root->left, val);
}
else if (val > root->val)
{
root->right = insertIntoBST(root->right, val);
}
return root;
}
};