LeetCode701. 二叉搜索树中的插入操作

难度:中等 题目描述:

给定二叉搜索树(BST)的根节点和要插入树中的值,将值插入二叉搜索树。 返回插入后二叉搜索树的根节点。 输入数据 保证 ,新值和原始二叉搜索树中的任意节点值都不同。 注意,可能存在多种有效的插入方式,只要树在插入后仍保持为二叉搜索树即可。 你可以返回任意有效的结果 。
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
          
   
public:
    TreeNode* insertIntoBST(TreeNode* root, int val) {
          
   
        TreeNode* tmp=new TreeNode(val);
        if(root==nullptr){
          
   
            root=tmp;
            return root;
        }
        if(val<root->val){
          
   
            if(root->left==nullptr){
          
   
                root->left=tmp;
            }else
            insertIntoBST(root->left,val);
        }else{
          
   
            if(root->right==nullptr){
          
   
                root->right=tmp;
            }else
            insertIntoBST(root->right,val);
        }
        return root;
    }
};
经验分享 程序员 微信小程序 职场和发展