Symmetric Tree recursively Algorithm
The Symmetric Tree Recursive Algorithm is an elegant and efficient method to determine if a given binary tree is symmetric or not. A binary tree is considered symmetric if it exhibits mirror-image symmetry, meaning that its left subtree is a mirror reflection of its right subtree, and vice versa. In other words, the tree looks the same when folded along its central axis. The algorithm leverages the concept of recursion, which is a technique where a function calls itself to solve smaller instances of the same problem, eventually reaching a base case.
The algorithm starts by checking if the root node is null, in which case the tree is considered symmetric. If the root node has both left and right children, the algorithm then checks if the values of these children are equal. If they are equal, the function proceeds by recursively checking if the left subtree's left child is equal to the right subtree's right child, and if the left subtree's right child is equal to the right subtree's left child. If these conditions are met, the function continues to traverse the tree in a similar fashion until either the base case (null nodes) is reached or an inequality is detected. In the end, the algorithm returns true if the tree is symmetric, and false otherwise. This approach is efficient and easy to understand, as it directly compares corresponding nodes in the left and right subtrees, eliminating the need for additional data structures or traversals.
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isSymmetric(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (root == NULL)
return true;
return dfs(root->left, root->right);
}
bool dfs(TreeNode *lhs, TreeNode *rhs) {
if (lhs == NULL && rhs == NULL)
return true;
if (lhs == NULL || rhs == NULL)
return false;
if (lhs->val == rhs->val) {
bool flag = dfs(lhs->left, rhs->right);
if (!flag) return false;
return dfs(lhs->right, rhs->left);
}
return false;
}
};