From 1582d072593cd2fc8abed038ff21e9666f990804 Mon Sep 17 00:00:00 2001 From: Kyle Lim Date: Sat, 5 Oct 2019 02:37:35 -0400 Subject: [PATCH] Solution of 669 --- 600-700q/669.py | 55 +++++++++++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 56 insertions(+) create mode 100644 600-700q/669.py diff --git a/600-700q/669.py b/600-700q/669.py new file mode 100644 index 0000000..7298f04 --- /dev/null +++ b/600-700q/669.py @@ -0,0 +1,55 @@ +''' +Given a binary search tree and the lowest and highest boundaries as L and R, trim the tree so that all its elements lies in [L, R] (R >= L). You might need to change the root of the tree, so the result should return the new root of the trimmed binary search tree. + +Example 1: +Input: + 1 + / \ + 0 2 + + L = 1 + R = 2 + +Output: + 1 + \ + 2 +Example 2: +Input: + 3 + / \ + 0 4 + \ + 2 + / + 1 + + L = 1 + R = 3 + +Output: + 3 + / + 2 + / + 1 +''' + +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + +class Solution: + def trimBST(self, root: TreeNode, L: int, R: int) -> TreeNode: + if not root: + return None + if L > root.val: + return self.trimBST(root.right, L, R) + elif R < root.val: + return self.trimBST(root.left, L, R) + root.left = self.trimBST(root.left, L, R) + root.right = self.trimBST(root.right, L, R) + return root diff --git a/README.md b/README.md index 9f03b51..9078ed0 100644 --- a/README.md +++ b/README.md @@ -120,6 +120,7 @@ Python solution of problems from [LeetCode](https://leetcode.com/). |681|[Next Closest Time ](https://leetcode.com/problems/next-closest-time)|[Python](./600-700q/681.py)|Medium| |674|[Longest Continuous Increasing Subsequence](https://leetcode.com/problems/longest-continuous-increasing-subsequence)|[Python](./600-700/674.py)|Easy| |673|[Number of Longest Increasing Subsequence](https://leetcode.com/problems/number-of-longest-increasing-subsequence)|[Python](./600-700q/673.py)|Medium| +|669|[Trim a Binary Search Tree](https://leetcode.com/problems/trim-a-binary-search-tree)|[Python](./600-700q/673.py)|Easy| ##### [Problems 400-500](./400-500Q/)