解题思路
按平衡二叉树规则递归往左右两边插,如果为空就新建一个节点
代码
class Solution {
public:
TreeNode* insertIntoBST(TreeNode* root, int val) {
if(root == nullptr) {
TreeNode* ans = new TreeNode(val);
return ans;
}
if(root->val < val) root->right = insertIntoBST(root->right, val);
else root->left = insertIntoBST(root->left, val);
return root;
}
};