Skip to content

Commit

Permalink
added solution for Two Sum BSTs.
Browse files Browse the repository at this point in the history
  • Loading branch information
ecgan committed Oct 5, 2019
1 parent a39b1ed commit 507c341
Show file tree
Hide file tree
Showing 3 changed files with 74 additions and 0 deletions.
7 changes: 7 additions & 0 deletions problems/two-sum-bsts/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# Two Sum BSTs

LeetCode #: [1214](https://leetcode.com/problems/two-sum-bsts/)

Difficulty: Medium.

Topics: Binary search tree.
23 changes: 23 additions & 0 deletions problems/two-sum-bsts/solution.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
const twoSumBSTs = (root1, root2, target) => {
if (root1 === null || root2 === null) {
return false
}

const sum = root1.val + root2.val

if (sum === target) {
return true
} else if (sum < target) {
return (
twoSumBSTs(root1, root2.right, target) ||
twoSumBSTs(root1.right, root2, target)
)
} else {
return (
twoSumBSTs(root1, root2.left, target) ||
twoSumBSTs(root1.left, root2, target)
)
}
}

module.exports = twoSumBSTs
44 changes: 44 additions & 0 deletions problems/two-sum-bsts/solution.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
const leettree = require('leettree')
const twoSumBSTs = require('./solution')

test('Example 1', () => {
const root1 = [2, 1, 4]
const root2 = [1, 0, 3]
const target = 5

const result = twoSumBSTs(
leettree.deserialize(root1),
leettree.deserialize(root2),
target
)

expect(result).toBe(true)
})

test('Example 2', () => {
const root1 = [0, -10, 10]
const root2 = [5, 1, 7, 0, 2]
const target = 18

const result = twoSumBSTs(
leettree.deserialize(root1),
leettree.deserialize(root2),
target
)

expect(result).toBe(false)
})

test('very small value', () => {
const root1 = [2, 1, 4]
const root2 = [1, 0, 3]
const target = -100

const result = twoSumBSTs(
leettree.deserialize(root1),
leettree.deserialize(root2),
target
)

expect(result).toBe(false)
})

0 comments on commit 507c341

Please sign in to comment.