![](https://img.haomeiwen.com/i6321855/77a40e20269d17ad.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 ;
}
网友评论