Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // O(height) - time complexity,
- // O(1) - space complexity.
- class Solution {
- public TreeNode trimBST(TreeNode root, int L, int R) {
- if (root == null) {
- return root;
- }
- while (root.val < L || R < root.val) {
- if (root.val < L) {
- root = root.right;
- } else {
- root = root.left;
- }
- }
- {
- TreeNode cur = root;
- while (cur != null) {
- while (cur.left != null && cur.left.val < L) {
- cur.left = cur.left.right;
- }
- cur = cur.left;
- }
- }
- {
- TreeNode cur = root;
- while (cur != null) {
- while (cur.right != null && R < cur.right.val) {
- cur.right = cur.right.left;
- }
- cur = cur.right;
- }
- }
- return root;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement