1
+ /*
2
+ Given the root of a binary tree, this function checks whether the tree is symmetric,
3
+ i.e., whether it is a mirror of itself around its center.
4
+
5
+ Time Complexity: O(n), where n is the number of nodes in the binary tree.
6
+ Space Complexity: O(n), due to the recursive stack space.
7
+
8
+ Approach:
9
+ - If the root is NULL, return true (base case).
10
+ - Recursively check if the left subtree of the root is mirrored with the right subtree.
11
+ - To check if two subtrees are mirrored, compare their left and right children recursively.
12
+
13
+ Example:
14
+ Input: root = [1,2,2,3,4,4,3]
15
+ Output: true
16
+
17
+ Input: root = [1,2,2,null,3,null,3]
18
+ Output: false
19
+ */
20
+
21
+ /* *
22
+ * Definition for a binary tree node.
23
+ * struct TreeNode {
24
+ * int val;
25
+ * TreeNode *left;
26
+ * TreeNode *right;
27
+ * TreeNode() : val(0), left(nullptr), right(nullptr) {}
28
+ * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
29
+ * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
30
+ * };
31
+ */
32
+ class Solution {
33
+ public:
34
+ bool isSymmetric (TreeNode* root) {
35
+ return dfs (root, root);
36
+ }
37
+
38
+ bool dfs (TreeNode* left, TreeNode* right) {
39
+ if (!left && !right)
40
+ return true ;
41
+ if (!left || !right)
42
+ return false ;
43
+
44
+ return left->val == right->val && dfs (left->left , right->right ) && dfs (left->right , right->left );
45
+ }
46
+ };
0 commit comments