Skip to content

Commit 8fb12cf

Browse files
committed
572
1 parent c2f50ab commit 8fb12cf

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

ruby/572-Subtree-of-Another-Tree.rb

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
def is_subtree(root, sub_root)
2+
return true if root.nil? && sub_root.nil?
3+
return true if sub_root.nil?
4+
return false if root.nil?
5+
6+
if same_tree?(root, sub_root)
7+
true
8+
else
9+
is_subtree(root.left, sub_root) ||
10+
is_subtree(root.right, sub_root)
11+
end
12+
end
13+
14+
def same_tree?(p, q)
15+
if p.nil? && q.nil?
16+
true
17+
elsif p && q
18+
(p.val == q.val) &&
19+
same_tree?(p.left, q.left) &&
20+
same_tree?(p.right, q.right)
21+
else
22+
false
23+
end
24+
end

0 commit comments

Comments
 (0)