Skip to content

Commit 8eaf024

Browse files
committed
Interview Questions: Elementary Symbol Tables - Use Morris Tree Traversal
1 parent 8c03b6f commit 8eaf024

File tree

2 files changed

+71
-0
lines changed

2 files changed

+71
-0
lines changed
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
### Inorder traversal with constant extra space
2+
3+
Design an algorithm to perform an inorder traversal of a binary search tree using only a constant amount of extra space.
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
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+
# Morris traversal
44+
45+
tree = build_tree([4, 2, 6, 1, 3, 5, 7])
46+
47+
# Use Morris Tree Traversal.
48+
def morris_traversal(current_root)
49+
while current_root
50+
if current_root.left
51+
current = current_root.left
52+
current = current.right while current.right
53+
current.right = current_root
54+
55+
temp = current_root
56+
current_root = current_root.left
57+
temp.left = nil
58+
else
59+
yield current_root.value
60+
current_root = current_root.right
61+
end
62+
end
63+
end
64+
65+
arr = []
66+
morris_traversal(tree) { |value| arr << value }
67+
fail unless arr == arr.sort
68+
p arr

0 commit comments

Comments
 (0)