Advertisement
halaluddin

Day15-Apr-Trim _a_BST-Recursive

Apr 15th, 2022
1,442
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 1.92 KB | None | 0 0
  1. class Solution {
  2.    
  3.     /**
  4.         Problem Link: https://leetcode.com/problems/trim-a-binary-search-tree/
  5.         Language:
  6.             Swift
  7.         Args:
  8.             root: Custom(TreeNode) data(class) type;
  9.             low: Int; most left child(lowest boundary) of trimed tree
  10.             high: Int; most right child(highest boundary) of trimed tree
  11.         Return:
  12.             Custom(TreeNode) data(class) type; return the trimed root node.
  13.         Complexity analysis:
  14.             Space: O(depth of triming method)
  15.             Time: O(n) - accroding to worst case.
  16.     */
  17.    
  18.     func trimBST(_ root: TreeNode?, _ low: Int, _ high: Int) -> TreeNode? {
  19.         /**
  20.             triming: Inner function
  21.             Args:
  22.                 current_node: Custom(TreeNode) data(class) type;
  23.             Return:
  24.                 Custom(TreeNode) data(class) type; return the trimed root node.
  25.         */
  26.         func triming(_ current_node: TreeNode?) -> TreeNode? {
  27.            
  28.             // return nil if currend node is null,
  29.             guard let current_node = current_node else { return nil }
  30.            
  31.             // if current value can pass the condition(low <= current value <= high)
  32.             // that means current node is a member of the trim subtree.
  33.             if (low <= current_node.val) && (current_node.val <= high) {
  34.                 current_node.left = triming(current_node.left)
  35.                 current_node.right = triming(current_node.right)
  36.                 return current_node
  37.             }
  38.            
  39.             // Cutting-up subtree according to the condition.
  40.             // 1. cutting the left subtree if currentnode value is less than lowest bound,
  41.             // 2. cutting the right subtree if current node value is greater than highest bound,
  42.             return current_node.val < low ? triming(current_node.right) : triming(current_node.left)
  43.         }
  44.        
  45.         return triming(root)
  46.     }
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement