Skip to content

Commit 6fd46f8

Browse files
authored
Add files via upload
This repository contains a C++ implementation of a function to determine if a binary tree is symmetric (i.e., a mirror of itself). The algorithm uses a recursive approach to compare the left and right subtrees of the tree. Key Features: Definition of the binary tree node structure (TreeNode). Recursive function isSymmetric to check for symmetry. Efficient time complexity of 𝑂 ( 𝑛 ) O(n), where 𝑛 n is the number of nodes in the tree.
1 parent 10eda2f commit 6fd46f8

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

101.Symmertic Tree.cpp

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* struct TreeNode {
4+
* int val;
5+
* TreeNode *left;
6+
* TreeNode *right;
7+
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
8+
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
9+
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
10+
* };
11+
*/
12+
class Solution {
13+
public:
14+
bool isSymmetric(TreeNode* root) {
15+
return isMirror(root, root); }
16+
17+
private :
18+
bool isMirror(TreeNode* left, TreeNode* right)
19+
{
20+
if (!left && !right) return true;
21+
if (!left || !right) return false;
22+
return (left->val == right->val) && isMirror(left-> left, right-> right) && isMirror(left-> right, right->left);
23+
}
24+
};

0 commit comments

Comments
 (0)