Skip to content

Commit e2d8f22

Browse files
committed
grind 75: symmetric-tree brute force sol
1 parent 89bd200 commit e2d8f22

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -337,6 +337,7 @@ solution of many challenges of [Leetcode](https://leetcode.com/), [Exercism](htt
337337
46. [3sum Closest](https://github.com/kumar91gopi/Algorithms-and-Data-Structures-in-Ruby/blob/master/leetcode/grind75/3sum_closest.rb)
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)
340+
49. [Symmetric Tree](https://github.com/kumar91gopi/Algorithms-and-Data-Structures-in-Ruby/blob/master/leetcode/grind75/symmetric_tree.rb)
340341

341342

342343
<a name="striver"/>

leetcode/grind75/symmetric_tree.rb

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
# Problem: https://leetcode.com/problems/symmetric-tree/description/
2+
=begin
3+
Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).
4+
Input: root = [1,2,2,3,4,4,3]
5+
Output: true
6+
Input: root = [1,2,2,null,3,null,3]
7+
Output: false
8+
=end
9+
10+
11+
#Definition for a binary tree node.
12+
# class TreeNode
13+
# attr_accessor :val, :left, :right
14+
# def initialize(val = 0, left = nil, right = nil)
15+
# @val = val
16+
# @left = left
17+
# @right = right
18+
# end
19+
# end
20+
# @param {TreeNode} root
21+
# @return {Boolean}
22+
23+
#Solution 1 (Brute force Recursive)
24+
def is_symmetric(root)
25+
return true if root.nil?
26+
compare_subtrees(root.left,root.right)
27+
end
28+
29+
def compare_subtrees(left_tree,right_tree)
30+
return true if left_tree.nil? and right_tree.nil?
31+
return false unless (left_tree&.val == right_tree&.val)
32+
return false unless compare_subtrees(left_tree&.right,right_tree&.left)
33+
compare_subtrees(left_tree&.left,right_tree&.right)
34+
end

0 commit comments

Comments
 (0)