/*
* @lc app=leetcode.cn id=669 lang=typescript
*
* [669] 修剪二叉搜索树
*/
// @lc code=start
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
function trimBST(root: TreeNode | null, low: number, high: number): TreeNode | null {}
// @lc code=end
function trimBST(root: TreeNode | null, low: number, high: number): TreeNode | null {
if (!root) return null
const dfs = (node: TreeNode | null) => {
if (!node) return null
;(node.left = dfs(node.left)), (node.right = dfs(node.right))
if (node.val <= high && node.val >= low) {
return node
} else if (node.val > high) {
return node.left
} else {
return node.right
}
}
return dfs(root)
}
test.each([
{ input: { root: [1, 0, 2], low: 1, high: 2 }, output: [1, null, 2] },
{ input: { root: [3, 0, 4, null, 2, null, null, 1], low: 1, high: 3 }, output: [3, 2, null, 1] },
])('input: root = $input.root, low = $input.low, high = $input.high', ({ input: { root, low, high }, output }) => {
expect(trimBST(BinaryTree.deserialize(root), low, high)).toEqual(BinaryTree.deserialize(output))
})