Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- /**
- Problem Link: https://leetcode.com/problems/trim-a-binary-search-tree/
- Language:
- Swift
- Args:
- root: Custom(TreeNode) data(class) type;
- low: Int; most left child(lowest boundary) of trimed tree
- high: Int; most right child(highest boundary) of trimed tree
- Return:
- Custom(TreeNode) data(class) type; return the trimed root node.
- Complexity analysis:
- Space: O(depth of triming method)
- Time: O(n) - accroding to worst case.
- */
- func trimBST(_ root: TreeNode?, _ low: Int, _ high: Int) -> TreeNode? {
- /**
- triming: Inner function
- Args:
- current_node: Custom(TreeNode) data(class) type;
- Return:
- Custom(TreeNode) data(class) type; return the trimed root node.
- */
- func triming(_ current_node: TreeNode?) -> TreeNode? {
- // return nil if currend node is null,
- guard let current_node = current_node else { return nil }
- // if current value can pass the condition(low <= current value <= high)
- // that means current node is a member of the trim subtree.
- if (low <= current_node.val) && (current_node.val <= high) {
- current_node.left = triming(current_node.left)
- current_node.right = triming(current_node.right)
- return current_node
- }
- // Cutting-up subtree according to the condition.
- // 1. cutting the left subtree if currentnode value is less than lowest bound,
- // 2. cutting the right subtree if current node value is greater than highest bound,
- return current_node.val < low ? triming(current_node.right) : triming(current_node.left)
- }
- return triming(root)
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement