【Leetcode】101. Symmetric Tree

Description

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

For example, this binary tree [1,2,2,3,4,4,3] is symmetric:

1
/ \
2 2
/ \ / \
3 4 4 3
But the following [1,2,2,null,3,null,3] is not:

1
/ \
2 2
\ \
3 3
Note:
Bonus points if you could solve it both recursively and iteratively.

Recursion

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# class TreeNode
# attr_accessor :val, :left, :right
# def initialize(val)
# @val = val
# @left, @right = nil, nil
# end
# end

# @param {TreeNode} root
# @return {Boolean}
def is_symmetric(root)
return true if root.nil?
mirror = lambda do |a, b|
return true if a.nil? && b.nil?
return false if a.nil? ^ b.nil? || a.val != b.val
mirror.call(a.left, b.right) && mirror.call(a.right, b.left)
end

mirror.call(root.left, root.right)
end

Iterative

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# class TreeNode
# attr_accessor :val, :left, :right
# def initialize(val)
# @val = val
# @left, @right = nil, nil
# end
# end

# @param {TreeNode} root
# @return {Boolean}
def is_symmetric(root)
return true if root.nil?

tree = []
tree << root.left
tree << root.right

while !tree.empty?
left = tree.shift
right = tree.pop

next if left.nil? && right.nil?
return false if left.nil? || right.nil?
return false if left.val != right.val

tree.unshift(left.left, left.right)
tree.push(right.left, right.right)
end

true
end