Advertisement
1988coder

701. Insert into a Binary Search Tree

Nov 25th, 2018
136
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.01 KB | None | 0 0
  1. /**
  2.  * Definition for a binary tree node.
  3.  * public class TreeNode {
  4.  *     int val;
  5.  *     TreeNode left;
  6.  *     TreeNode right;
  7.  *     TreeNode(int x) { val = x; }
  8.  * }
  9.  */
  10.  
  11. /*
  12. Iterative Solution
  13.  
  14. Time Complexity: O(N) - If the tree is skewed it will visit all nodes.
  15. Space Complexity: O(1)
  16. N = Total number of nodes in the binary search tree.
  17. */
  18. class Solution {
  19.     public TreeNode insertIntoBST(TreeNode root, int val) throws IllegalArgumentException {
  20.         if (root == null) {
  21.             return new TreeNode(val);
  22.         }
  23.         TreeNode cur = root;
  24.         while (true) {
  25.             if (val == cur.val) {
  26.                 throw new IllegalArgumentException("val already exists in the given binary search tree");
  27.             }
  28.             if (val > cur.val) {
  29.                 if (cur.right != null) {
  30.                     cur = cur.right;
  31.                 } else {
  32.                     cur.right = new TreeNode(val);
  33.                     break;
  34.                 }
  35.             } else {
  36.                 if (cur.left != null) {
  37.                     cur = cur.left;
  38.                 } else {
  39.                     cur.left = new TreeNode(val);
  40.                     break;
  41.                 }
  42.             }
  43.         }
  44.         return root;
  45.     }
  46. }
  47.  
  48.  
  49. /*
  50. Recursive Solution
  51.  
  52. Time Complexity: O(N) - If the tree is skewed it will visit all nodes.
  53. Space Complexity: O(H)
  54. N = Total number of nodes in the binary search tree.
  55. H = Height of the tree (Recursion Stack).
  56. */
  57. class Solution {
  58.     public TreeNode insertIntoBST(TreeNode root, int val) throws IllegalArgumentException {
  59.         if (root == null) {
  60.             return new TreeNode(val);
  61.         }
  62.         if (val == root.val) {
  63.             throw new IllegalArgumentException("val already exists in the given binary search tree");
  64.         }
  65.         if (val > root.val) {
  66.             root.right = insertIntoBST(root.right, val);
  67.         } else {
  68.             root.left = insertIntoBST(root.left, val);
  69.         }
  70.         return root;
  71.     }
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement