Symmetric Tree iteratively Algorithm
The Symmetric Tree Iterative Algorithm is an algorithm used to determine if a binary tree is symmetric, which means the tree is a mirror image of itself. In other words, the left subtree of a node should be a mirror reflection of the right subtree of the node. This algorithm is a popular problem-solving approach in computer science, often encountered in coding interviews and competitive programming. It uses an iterative method, leveraging data structures like queues or stacks to traverse the tree and compare the left and right subtrees at each level.
The algorithm starts by initializing an empty queue and pushing the root node's left and right children onto the queue. Then, while the queue is not empty, it dequeues two nodes at a time, comparing their values for symmetry. If the dequeued nodes are both null, the algorithm continues to the next pair; if only one of the nodes is null, the tree is not symmetric. If both nodes have values, the algorithm checks their symmetry and enqueues their children in a specific order: first the left child of the first node and the right child of the second node, then the right child of the first node and the left child of the second node. The algorithm proceeds until the queue is empty or a pair of nodes is found to be asymmetric. If the queue is empty and no asymmetric pair is found, the binary tree is symmetric.
/**
* 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;
queue<TreeNode*> lhs, rhs;
lhs.push(root->left);
rhs.push(root->right);
while (!lhs.empty() && !rhs.empty()) {
TreeNode *l = lhs.front(); lhs.pop();
TreeNode *r = rhs.front(); rhs.pop();
if (l == NULL && r == NULL) continue;
if (l == NULL || r == NULL) return false;
if (l->val != r->val) return false;
lhs.push(l->left); lhs.push(l->right);
rhs.push(r->right); rhs.push(r->left);
}
if (lhs.empty() && rhs.empty())
return true;
else
return false;
}
};