Skip to content

Commit 6b098d1

Browse files
committed
Find left most node on a binary tree problem.
1 parent 0a210f3 commit 6b098d1

File tree

2 files changed

+92
-1
lines changed

2 files changed

+92
-1
lines changed

Interview-Questions/count_max_sub_arr.rb

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,6 @@ def count_subarrays(arr)
2121
end
2222
end
2323
j = i-1
24-
p i
2524
while(j >= 0)
2625
if(arr[i] > arr[j])
2726
count += 1

Interview-Questions/left_most_node.rb

Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
=begin
2+
Signature
3+
int visibleNodes(Node root) {
4+
Input
5+
The root node of a tree, where the number of nodes is between 1 and 1000, and the value of each node is between 0 and 10,000,000,000
6+
Output
7+
An int representing the number of visible nodes.
8+
Example
9+
8 <------ root
10+
/ \
11+
3 10
12+
/ \ \
13+
1 6 14
14+
/ \ /
15+
4 7 13
16+
output = 4
17+
=end
18+
19+
class Node
20+
attr_reader :value
21+
attr_accessor :left, :right
22+
23+
def initialize(value)
24+
@value = value
25+
@left = nil
26+
@right = nil
27+
end
28+
end
29+
30+
class BinaryTree
31+
attr_reader :root
32+
33+
def initialize
34+
@root = nil
35+
end
36+
37+
def insert(value)
38+
new_node = Node.new(value)
39+
unless @root
40+
@root = new_node
41+
else
42+
temp_node = @root
43+
while(temp_node)
44+
if(temp_node.value > value)
45+
unless(temp_node.left)
46+
temp_node.left = new_node
47+
return
48+
end
49+
temp_node = temp_node.left
50+
else
51+
unless(temp_node.right)
52+
temp_node.right = new_node
53+
return
54+
end
55+
temp_node = temp_node.right
56+
end
57+
end
58+
end
59+
end
60+
end
61+
62+
63+
def visible_node(root, left_most_node = {}, level=0)
64+
if(level == 0)
65+
left_most_node[level] = root.value
66+
end
67+
return left_most_node[level-1] unless root
68+
level = level+1
69+
unless(left_most_node[level])
70+
if(root.left)
71+
left_most_node[level] = root.left.value
72+
elsif(root.right)
73+
left_most_node[level] = root.right.value
74+
end
75+
end
76+
visible_node(root.left, left_most_node, level)
77+
visible_node(root.right, left_most_node, level)
78+
end
79+
80+
bst = BinaryTree.new
81+
bst.insert(8)
82+
bst.insert(3)
83+
bst.insert(1)
84+
bst.insert(6)
85+
bst.insert(4)
86+
bst.insert(7)
87+
bst.insert(10)
88+
bst.insert(14)
89+
bst.insert(13)
90+
bst.insert(15)
91+
bst.insert(16)
92+
p visible_node(bst.root)

0 commit comments

Comments
 (0)