SHARE
TWEET

task4 (updated)

a guest Aug 25th, 2019 61 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // O(height) - time complexity,
  2. // O(1) - space complexity.
  3. class Solution {
  4.     public TreeNode trimBST(TreeNode root, int L, int R) {
  5.         if (root == null) {
  6.             return root;
  7.         }
  8.         while (root.val < L || R < root.val) {
  9.             if (root.val < L) {
  10.                 root = root.right;
  11.             } else {
  12.                 root = root.left;
  13.             }
  14.         }
  15.         {
  16.             TreeNode cur = root;
  17.             while (cur != null) {
  18.                 while (cur.left != null && cur.left.val < L) {
  19.                     cur.left = cur.left.right;
  20.                 }
  21.                 cur = cur.left;
  22.             }
  23.         }
  24.         {
  25.             TreeNode cur = root;
  26.             while (cur != null) {
  27.                 while (cur.right != null && R < cur.right.val) {
  28.                     cur.right = cur.right.left;
  29.                 }
  30.                 cur = cur.right;
  31.             }
  32.         }
  33.         return root;
  34.     }
  35. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top