diff --git a/Symmetric Tree/README.md b/Symmetric Tree/README.md new file mode 100644 index 0000000..4037d46 --- /dev/null +++ b/Symmetric Tree/README.md @@ -0,0 +1,25 @@ +

Symmetric Tree


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:

+ + + +

 

+Follow up: Could you solve it both recursively and iteratively?
diff --git a/Symmetric Tree/symmetric-tree.cpp b/Symmetric Tree/symmetric-tree.cpp new file mode 100644 index 0000000..7e3acc6 --- /dev/null +++ b/Symmetric Tree/symmetric-tree.cpp @@ -0,0 +1,29 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + bool isSameTree(TreeNode* p, TreeNode* q){ + if(p==NULL && q==NULL) + return true; + if(p==NULL || q==NULL) + return false; + if(p->val!=q->val) + return false; + return isSameTree(p->left,q->right)&&isSameTree(p->right,q->left); +} + + bool isSymmetric(TreeNode* root){ + if(root==NULL) + return true; + return isSameTree(root->left,root->right); + } +};