Easy
Given the root
of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).
Example 1:
Input: root = [1,2,2,3,4,4,3]
Output: true
Example 2:
Input: root = [1,2,2,null,3,null,3]
Output: false
Constraints:
[1, 1000]
.-100 <= Node.val <= 100
Follow up: Could you solve it both recursively and iteratively?
; Definition for a binary tree node.
#|
; val : integer?
; left : (or/c tree-node? #f)
; right : (or/c tree-node? #f)
(struct tree-node
(val left right) #:mutable #:transparent)
; constructor
(define (make-tree-node [val 0])
(tree-node val #f #f))
|#
(define/contract (is-symmetric root)
(-> (or/c tree-node? #f) boolean?)
(define (two-symmetric? left right)
(cond
[(and (not left) (not right )) #t]
[(and left (not right )) #f]
[(and (not left) right) #f]
[(not (equal? (tree-node-val left) (tree-node-val right))) #f]
[else
(and (two-symmetric? (tree-node-left left) (tree-node-right right))
(two-symmetric? (tree-node-right left) (tree-node-left right)))]))
(two-symmetric? (tree-node-left root) (tree-node-right root)))