|
| 1 | +/** |
| 2 | + * 669. Trim a Binary Search Tree |
| 3 | + * https://leetcode.com/problems/trim-a-binary-search-tree/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * Given the root of a binary search tree and the lowest and highest boundaries as low and high, |
| 7 | + * trim the tree so that all its elements lies in [low, high]. Trimming the tree should not change |
| 8 | + * the relative structure of the elements that will remain in the tree (i.e., any node's descendant |
| 9 | + * should remain a descendant). It can be proven that there is a unique answer. |
| 10 | + * |
| 11 | + * Return the root of the trimmed binary search tree. Note that the root may change depending on |
| 12 | + * the given bounds. |
| 13 | + */ |
| 14 | + |
| 15 | +/** |
| 16 | + * Definition for a binary tree node. |
| 17 | + * function TreeNode(val, left, right) { |
| 18 | + * this.val = (val===undefined ? 0 : val) |
| 19 | + * this.left = (left===undefined ? null : left) |
| 20 | + * this.right = (right===undefined ? null : right) |
| 21 | + * } |
| 22 | + */ |
| 23 | +/** |
| 24 | + * @param {TreeNode} root |
| 25 | + * @param {number} low |
| 26 | + * @param {number} high |
| 27 | + * @return {TreeNode} |
| 28 | + */ |
| 29 | +var trimBST = function(root, low, high) { |
| 30 | + if (!root) return null; |
| 31 | + |
| 32 | + if (root.val < low) return trimBST(root.right, low, high); |
| 33 | + if (root.val > high) return trimBST(root.left, low, high); |
| 34 | + root.left = trimBST(root.left, low, high); |
| 35 | + root.right = trimBST(root.right, low, high); |
| 36 | + |
| 37 | + return root; |
| 38 | +}; |
0 commit comments