首先不管三七二十一!做出来了就不错!!
虽然有点繁琐~~~~~
思路很简单:
根据二叉搜索树的特性来的。直接拿 val 和根结点的值作比较。如果大,查看左边是否能插入,不能继续往下递归找。 如果小也是同理。
class Solution {
public:
TreeNode* insertIntoBST(TreeNode* root, int val) {
// 直接与根结点比较?
if(root == nullptr)
return new TreeNode(val);
if(val < root->val && root->left == nullptr)
root->left = new TreeNode(val);
if(val > root->val && root->right == nullptr)
root->right = new TreeNode(val);
if(val < root->val && root->left != nullptr)
insertIntoBST(root->left, val);
if(val > root->val && root->right != nullptr)
insertIntoBST(root->right, val);
return root;
}
};
看了题解
注意这里在递归调用函数的时候,是去接住返回值了的。因为接住的就是上一层返回来的新创建的结点。然后再将根结点返回。
class Solution {
public:
TreeNode* insertIntoBST(TreeNode* root, int val) {
if(root == nullptr)
return new TreeNode(val);
if(root->val > val)
root->left = insertIntoBST(root->left, val);
else if(root->val < val)
root->right = insertIntoBST(root->right, val);
return root;
}
};