/**
* 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){
struct TreeNode* t=(struct TreeNode*)malloc(sizeof(struct TreeNode));
t->left=NULL;
t->right=NULL;
t->val=val;
return t;
}
struct TreeNode* temp=root;
while(temp){
if(temp->val>val){
if(temp->left){
temp=temp->left;
}else{
struct TreeNode* t=(struct TreeNode*)malloc(sizeof(struct TreeNode));
t->left=NULL;
t->right=NULL;
t->val=val;
temp->left=t;
break;
}
}else{
if(temp->right){
temp=temp->right;
}else{
struct TreeNode* t=(struct TreeNode*)malloc(sizeof(struct TreeNode));
t->left=NULL;
t->right=NULL;
t->val=val;
temp->right=t;
break;
}
}
}
return root;
}
结果:
标签:right,TreeNode,struct,temp,701,二叉,val,树中,left From: https://www.cnblogs.com/llllmz/p/18057482