Skip to content

Commit 5e3c316

Browse files
committed
Binary Tree paths and add helper for deserilze the string to node
1 parent 4a1f901 commit 5e3c316

File tree

2 files changed

+85
-0
lines changed

2 files changed

+85
-0
lines changed

Binary Tree Paths/Solution.rb

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
require '../helper.rb'
2+
3+
# @param {TreeNode} root
4+
# @return {String[]}
5+
def binary_tree_paths(root)
6+
7+
return [] if root.nil?
8+
parent_path = Hash.new
9+
s=[];
10+
paths=[];
11+
12+
s.push(root)
13+
14+
until s.empty?
15+
16+
r=s.pop();
17+
#puts r.val
18+
#puts ''
19+
p=''
20+
if parent_path[r].nil?
21+
p = r.val.to_s
22+
else
23+
#puts parent_path[r]
24+
#puts r.val
25+
p = "#{parent_path[r]}->#{r.val}"
26+
end
27+
28+
#puts p
29+
30+
if r.left.nil? && r.right.nil?
31+
#puts 'Its leafnode'
32+
paths.push(p)
33+
end
34+
35+
if !r.right.nil?
36+
s.push(r.right)
37+
parent_path[r.right]=p.to_s
38+
end
39+
40+
if !r.left.nil?
41+
s.push(r.left)
42+
parent_path[r.left]=p.to_s
43+
end
44+
end
45+
paths
46+
end
47+
48+
data = [1,2,3,4,nil,nil,5]
49+
node = deserialize(data)
50+
print binary_tree_paths(node)

helper.rb

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
# Definition for a binary tree node.
2+
class TreeNode
3+
attr_accessor :val, :left, :right
4+
def initialize(val)
5+
@val = val
6+
@left, @right = nil, nil
7+
end
8+
end
9+
10+
# Deserialize string to root object
11+
def deserialize(data)
12+
return data if data.nil?
13+
q=[]
14+
15+
root = TreeNode.new(data.shift)
16+
q.push(root)
17+
18+
until data.empty?
19+
t = q.shift
20+
l = data.shift
21+
r = data.shift
22+
23+
unless l.nil?
24+
t.left = TreeNode.new(l)
25+
q.push(t.left)
26+
end
27+
28+
unless r.nil?
29+
t.right = TreeNode.new(r)
30+
q.push(t.right)
31+
end
32+
33+
end
34+
root
35+
end

0 commit comments

Comments
 (0)