3.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

Iterative Solution using Queue

Note:- Level order traversal of a Symmetric binary tree is palindromic.

class Solution
{
public:
    bool isSymmetric(TreeNode *root)
    {

        if (root == NULL)
        {
            return true;
        }

        if (!root->left && !root->right)
        {
            return true;
        }
        else if (!root->left || !root->right)
        {
            return false;
        }

        bool res = true;
        queue<TreeNode *> q;
        q.push(root->left);
        q.push(root->right);

        while (!q.empty())
        {

            TreeNode *leftNode = q.front();
            q.pop();
            TreeNode *rightNode = q.front();
            q.pop();

            if (leftNode->val != rightNode->val)
            {
                res = false;
                break;
            }

            if (leftNode->left && rightNode->right)
            {
                q.push(leftNode->left);
                q.push(rightNode->right);
            }
            else if (leftNode->left || rightNode->right)
            {
                res = false;
                break;
            }

            if (leftNode->right && rightNode->left)
            {
                q.push(leftNode->right);
                q.push(rightNode->left);
            }
            else if (leftNode->right || rightNode->left)
            {
                res = false;
                break;
            }
        }

        return res;
    }
};

Solution: (Recursion)

Last updated

Was this helpful?