-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path45.2_validate_tree.rb
59 lines (47 loc) · 1.44 KB
/
45.2_validate_tree.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# frozen_string_literal: true
# Given a binary tree, containing unique values, determine if it is a valid binary search tree.
# Note: the invariants of a binary search tree (in our case)
# are all values to the left of a given node are less than the current node’s value,
# all values to the right of a given node are greater than the current node’s value,
# and both the left and right subtrees of a given node must also be binary search trees.
# Ex: Given the following binary tree…
# 1
# / \
# 2 3
# return false
# Ex: Given the following tree…
# 2
# / \
# 1 3
# return true
require_relative '../test_helper'
class Node
attr_accessor :val, :left, :right
def initialize(val: 0, left: nil, right: nil)
@val = val
@left = left
@right = right
end
end
class Solution
def valid_bst?(node: root, min: nil, max: nil)
return true if node.nil?
return false if (min && node.val <= min) || (max && node.val > max)
valid_bst?(node: node.left, min:, max: node.val) &&
valid_bst?(node: node.right, min: node.val, max:)
end
end
class Test < Minitest::Test
def test_1
n3 = Node.new(val: 3)
n2 = Node.new(val: 2)
n1 = Node.new(val: 1, left: n2, right: n3)
assert_equal false, Solution.new.valid_bst?(node: n1)
end
def test_2
n3 = Node.new(val: 3)
n2 = Node.new(val: 1)
n1 = Node.new(val: 2, left: n2, right: n3)
assert_equal true, Solution.new.valid_bst?(node: n1)
end
end