美文网首页
701. Insert into a Binary Search

701. Insert into a Binary Search

作者: 是嘤嘤嘤呀 | 来源:发表于2020-04-04 15:03 被阅读0次
image.png

代码

// c++
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* insertIntoBST(TreeNode* root, int val) {
        if (root == NULL) {
            TreeNode* rr = new TreeNode(val);
            return rr ;
        }
        if(val>root->val) root->right  = insertIntoBST(root->right,val) ;
        else  root->left =  insertIntoBST(root->left,val);
        return root ;     
    }
};
// 优秀的C代码
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */


struct TreeNode* insertIntoBST(struct TreeNode* root, int val){
   if (root == NULL) {
            struct TreeNode* rr = (struct TreeNode *)calloc(1, sizeof(struct TreeNode));
            rr->val = val;
            return rr ;
        }
        if(val>root->val) root->right  = insertIntoBST(root->right,val) ;
        else  root->left =  insertIntoBST(root->left,val);
        return root ; 
}

相关文章

网友评论

      本文标题:701. Insert into a Binary Search

      本文链接:https://www.haomeiwen.com/subject/bbrjphtx.html