https://leetcode-cn.com/problems/insert-into-a-binary-search-tree/
这也能递归是我没有想到的。。。
class Solution {
public TreeNode insertIntoBST(TreeNode root, int val) {
if (root == null) {
return new TreeNode(val);
}
if (val < root.val) {
root.left = insertIntoBST(root.left, val);
} else {
root.right = insertIntoBST(root.right, val);
}
return root;
}
}
//递归代码。。。
非递归:
/**
* 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) {
if (root == nullptr) {
return new TreeNode(val);
}
TreeNode* p = root;
while(p!=NULL){
if(p->val > val){
if(p->left != NULL){
p = p->left;
}else{
p->left = new TreeNode(val);
// p = NULL;
break;
}
}else{
if(p->right != NULL){
p = p->right;
}else{
p->right = new TreeNode{val};
// p = NULL;
break;
}
}
}
return root;
}
};