Skip to content

Commit a04675d

Browse files
committed
leetcode/grind:50 subtree of another tree-brute force recursive
1 parent a61c51a commit a04675d

File tree

2 files changed

+38
-1
lines changed

2 files changed

+38
-1
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -338,7 +338,7 @@ solution of many challenges of [Leetcode](https://leetcode.com/), [Exercism](htt
338338
47. [Min Stack](https://github.com/kumar91gopi/Algorithms-and-Data-Structures-in-Ruby/blob/master/leetcode/grind75/min_stack.rb)
339339
48. [Balanced Binary tree](https://github.com/kumar91gopi/Algorithms-and-Data-Structures-in-Ruby/blob/master/leetcode/grind75/balanced_binary_tree.rb)
340340
49. [Symmetric Tree](https://github.com/kumar91gopi/Algorithms-and-Data-Structures-in-Ruby/blob/master/leetcode/grind75/symmetric_tree.rb)
341-
341+
50. [Subtree of Another Tree](https://github.com/kumar91gopi/Algorithms-and-Data-Structures-in-Ruby/blob/master/leetcode/grind75/subtree_of_another_tree.rb)
342342

343343
<a name="striver"/>
344344

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
# Problem: https://leetcode.com/problems/subtree-of-another-tree/description/
2+
=begin
3+
Given the roots of two binary trees root and subRoot,
4+
return true if there is a subtree of root with the same structure and node values of subRoot and false otherwise.
5+
A subtree of a binary tree tree is a tree that consists of a node in tree and all of this node's descendants.
6+
The tree tree could also be considered as a subtree of itself.
7+
=end
8+
9+
# Definition for a binary tree node.
10+
# class TreeNode
11+
# attr_accessor :val, :left, :right
12+
# def initialize(val = 0, left = nil, right = nil)
13+
# @val = val
14+
# @left = left
15+
# @right = right
16+
# end
17+
# end
18+
# @param {TreeNode} root
19+
# @param {TreeNode} sub_root
20+
# @return {Boolean}
21+
22+
# Solution 1 (Brute force recursive)
23+
def is_subtree(root, sub_root)
24+
return true if sub_root.nil?
25+
return false if root.nil?
26+
is_found = false
27+
if root.val == sub_root.val
28+
return true if is_same_tree(root, sub_root)
29+
end
30+
is_subtree(root.left, sub_root) || is_subtree(root.right, sub_root)
31+
end
32+
33+
def is_same_tree(root1, root2)
34+
return true if root1.nil? and root2.nil?
35+
return false if root1.nil? or root2.nil?
36+
root1.val == root2.val and is_same_tree(root1.left, root2.left) and is_same_tree(root1.right, root2.right)
37+
end

0 commit comments

Comments
 (0)