Skip to content

Commit

Permalink
leetcode: 669. Trim a Binary Search Tree
Browse files Browse the repository at this point in the history
  • Loading branch information
ympons committed Feb 10, 2021
1 parent bf6607d commit 73268db
Show file tree
Hide file tree
Showing 3 changed files with 97 additions and 0 deletions.
18 changes: 18 additions & 0 deletions leetcode/0669-trim-a-binary-search-tree/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# 669. Trim a Binary Search Tree

Given the `root` of a binary search tree and the lowest and highest boundaries as `low` and `high`, trim the tree so that all its elements lies in `[low, high]`. Trimming the tree should **not** change the relative structure of the elements that will remain in the tree (i.e., any node's descendant should remain a descendant). It can be proven that there is a **unique answer**.

Return **the root of the trimmed binary search tree**. Note that the root may change depending on the given bounds.

**Example:**
```
Input: root = [1,0,2], low = 1, high = 2
Output: [1,null,2]
```

**Constraints:**
- The number of nodes in the tree in the range `[1, 10^4]`.
- `0 <= Node.val <= 10^4`
- The value of each node in the tree is **unique**.
- `root` is guaranteed to be a valid binary search tree.
- `0 <= low <= high <= 10^4`
23 changes: 23 additions & 0 deletions leetcode/0669-trim-a-binary-search-tree/trim_bst.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package leetcode

// TreeNode defines a binary tree node.
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}

func trimBST(root *TreeNode, low int, high int) *TreeNode {
if root == nil {
return root
}
if root.Val > high {
return trimBST(root.Left, low, high)
}
if root.Val < low {
return trimBST(root.Right, low, high)
}
root.Left = trimBST(root.Left, low, high)
root.Right = trimBST(root.Right, low, high)
return root
}
56 changes: 56 additions & 0 deletions leetcode/0669-trim-a-binary-search-tree/trim_bst_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
package leetcode

import (
"testing"

"github.com/stretchr/testify/assert"
)

func TestTrimBST(t *testing.T) {
assert := assert.New(t)
for _, test := range tests {
assert.Equal(test.expected, trimBST(test.root, test.low, test.high))
}
}

var tests = []struct {
root *TreeNode
low, high int
expected *TreeNode
}{
{
root: &TreeNode{
Val: 1,
Left: &TreeNode{Val: 0},
Right: &TreeNode{Val: 2},
},
low: 1,
high: 2,
expected: &TreeNode{
Val: 1,
Right: &TreeNode{Val: 2},
},
},
{
root: &TreeNode{
Val: 3,
Left: &TreeNode{
Val: 0,
Right: &TreeNode{
Val: 2,
Left: &TreeNode{Val: 1},
},
},
Right: &TreeNode{Val: 4},
},
low: 1,
high: 3,
expected: &TreeNode{
Val: 3,
Left: &TreeNode{
Val: 2,
Left: &TreeNode{Val: 1},
},
},
},
}

0 comments on commit 73268db

Please sign in to comment.