https://leetcode.com/problems/insert-into-a-binary-search-tree/

1. Use iteration:

  1. //
  2. /**
  3. * Definition for a binary tree node.
  4. * struct TreeNode {
  5. * int val;
  6. * TreeNode *left;
  7. * TreeNode *right;
  8. * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
  9. * };
  10. */
  11. class Solution {
  12. public:
  13. TreeNode* insertIntoBST(TreeNode* root, int val) {
  14. TreeNode* insert = new TreeNode(val);
  15. if(!root){
  16. return insert;
  17. }
  18. TreeNode* curr = root;
  19. while(curr){
  20. if(val > curr->val){
  21. if(curr->right)
  22. curr = curr->right;
  23. else{
  24. curr->right = insert;
  25. break;
  26. }
  27. } else if (val < curr->val){
  28. if(curr->left)
  29. curr = curr->left;
  30. else{
  31. curr->left = insert;
  32. break;
  33. }
  34. }
  35. }
  36. return root;
  37. }
  38. };

2. Use BST:

  1. //136 ms 48.8 MB
  2. /**
  3. * Definition for a binary tree node.
  4. * struct TreeNode {
  5. * int val;
  6. * TreeNode *left;
  7. * TreeNode *right;
  8. * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
  9. * };
  10. */
  11. class Solution {
  12. public:
  13. TreeNode* insertIntoBST(TreeNode* root, int val) {
  14. if(!root){
  15. return new TreeNode(val);
  16. }
  17. if(val > root->val)
  18. root->right = insertIntoBST(root->right, val);
  19. else if (val < root->val)
  20. root->left = insertIntoBST(root->left, val);
  21. return root;
  22. }
  23. };