Skip to content

Commit 8c03b6f

Browse files
committed
Interview Questions: Elementary Symbol Tables
1 parent 2bacb48 commit 8c03b6f

File tree

3 files changed

+83
-0
lines changed

3 files changed

+83
-0
lines changed
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
### Java autoboxing and equals()
2+
3+
Consider two double values `a` and `b` and their corresponding `Double` values `x` and `y`.
4+
5+
- Find values such that `(a==b)` is `true` but `x.equals(y)` is `false`.
6+
- Find values such that `(a==b)` is `false` but `x.equals(y)` is `true`.
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
### Check if a binary tree is a BST
2+
3+
Given a binary tree where each Node contains a key, determine whether it is a binary search tree. Use extra space proportional to the height of the tree.
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
class TreeNode
2+
attr_accessor :value, :left, :right
3+
4+
def initialize(value = 0, left = nil, right = nil)
5+
@value = value
6+
@left = left
7+
@right = right
8+
end
9+
10+
def to_a
11+
arr = []
12+
arr += left.to_a if left
13+
arr << value
14+
arr += right.to_a if right
15+
arr
16+
end
17+
end
18+
19+
def build_tree(array)
20+
root = TreeNode.new(array[0])
21+
queue = [root]
22+
i = 1
23+
24+
while i < array.size
25+
current = queue.shift
26+
27+
if array[i]
28+
current.left = TreeNode.new(array[i])
29+
queue << current.left
30+
end
31+
i += 1
32+
33+
if array[i]
34+
current.right = TreeNode.new(array[i])
35+
queue << current.right
36+
end
37+
i += 1
38+
end
39+
40+
root
41+
end
42+
43+
# Given a binary tree where each Node contains a key, determine whether it is a binary search tree. Use extra space proportional to the height of the tree.
44+
45+
bsts = []
46+
bsts << build_tree([4, 2, 6, 1, 3, 5, 7])
47+
bsts << build_tree([1, nil, 2])
48+
bsts << build_tree([3, 2, nil, 1])
49+
bsts << build_tree([5, 2, 8, 1, 3, nil, 9, nil, nil, nil, 4])
50+
51+
non_bsts = []
52+
non_bsts << build_tree([3, 4, 1, nil, 2])
53+
non_bsts << build_tree([1, 2, 3, 4, 5, 6, 7])
54+
non_bsts << build_tree([4, 2, 6, 1, 3, 7, 5])
55+
56+
def is_bst?(root)
57+
if root.left
58+
return false if root.left.value > root.value
59+
return false unless is_bst?(root.left)
60+
end
61+
if root.right
62+
return false if root.right.value < root.value
63+
return false unless is_bst?(root.right)
64+
end
65+
true
66+
end
67+
68+
bsts.each do |tree|
69+
fail unless is_bst?(tree)
70+
end
71+
72+
non_bsts.each do |tree|
73+
fail if is_bst?(tree)
74+
end

0 commit comments

Comments
 (0)