Skip to content

Commit

Permalink
572
Browse files Browse the repository at this point in the history
  • Loading branch information
TedTran2019 committed Jul 8, 2022
1 parent c2f50ab commit 8fb12cf
Showing 1 changed file with 24 additions and 0 deletions.
24 changes: 24 additions & 0 deletions ruby/572-Subtree-of-Another-Tree.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
def is_subtree(root, sub_root)
return true if root.nil? && sub_root.nil?
return true if sub_root.nil?
return false if root.nil?

if same_tree?(root, sub_root)
true
else
is_subtree(root.left, sub_root) ||
is_subtree(root.right, sub_root)
end
end

def same_tree?(p, q)
if p.nil? && q.nil?
true
elsif p && q
(p.val == q.val) &&
same_tree?(p.left, q.left) &&
same_tree?(p.right, q.right)
else
false
end
end

0 comments on commit 8fb12cf

Please sign in to comment.