1+ # TO DO: Given the root of a binary tree,
2+ # check whether it is a mirror of itself
3+ # (i.e., symmetric around its center).
4+ #
5+ # Definition for a binary tree node.
6+ from typing import Optional
7+
8+
9+ class TreeNode :
10+ def __init__ (self , val = 0 , left = None , right = None ):
11+ self .val = val
12+ self .left = left
13+ self .right = right
14+ #
15+ # Example №1
16+ # Input: root = [1,2,2,3,4,4,3]
17+ # Output: true
18+ #
19+ # Example №2
20+ # Input: root = [1,2,2,null,3,null,3]
21+ # Output: false
22+ #
23+ def tree_go (root_r : Optional [TreeNode ], root_l : Optional [TreeNode ]):
24+ if root_r is None and root_l is None :
25+ return True
26+ elif root_r is None or root_l is None :
27+ return False
28+ return (root_r .val == root_l .val
29+ and
30+ tree_go (root_r = root_r .left , root_l = root_l .right )
31+ and
32+ tree_go (root_r = root_r .right , root_l = root_l .left )
33+ )
34+
35+ def check_tree (root : Optional [TreeNode ]) -> bool :
36+ if not root :
37+ return True
38+ else :
39+ return tree_go (root_l = root .left , root_r = root .right )
40+
41+
42+ if __name__ == "__main__" :
43+ example_root = TreeNode (val = 1 ,
44+ left = TreeNode (val = 2 ,
45+ left = None ,
46+ right = TreeNode (val = 3 , left = None , right = None )),
47+ right = TreeNode (val = 2 ,
48+ left = TreeNode (val = 3 , left = None , right = None ),
49+ right = TreeNode (val = 3 , left = None , right = None ))
50+ )
51+ print (check_tree (example_root ))
0 commit comments