Leetcode 101. symmetric binary tree

Title Description

Given a binary tree, check whether it is mirror symmetric.

 

Example

For example, a binary tree [1,2,2,3,4,4,3] is symmetric.

    1
   / \
  2   2
 / \ / \
3  4 4  3
But the following [1,2,2,null,3,null,3] is not mirror symmetric:

    1
   / \
  2   2
   \   \
   3    3

 

Train of thought 1

According to the meaning of the question, symmetry is two nodes n1 and n2. Compare the left sub-node of n1 with the right sub-node of n2, whether the right sub-node of n1 is equal to the left sub-node of n2.

Recursive implementation.

 

Code

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool isSymmetric(TreeNode* root) {
        if (!root)
            return true;
        return isSymmetric(root->left, root->right);
    }
    
    bool isSymmetric(TreeNode* leftNode, TreeNode* rightNode){
        if (!leftNode && !rightNode)
            return true;
        if (!leftNode || !rightNode || leftNode->val != rightNode->val)
            return false;
        return (isSymmetric(leftNode->left, rightNode->right) && isSymmetric(leftNode->right, rightNode->left));
    }
};

 

Train of thought 2

Iterative implementation.

 

Code

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool isSymmetric(TreeNode* root) {
        if (!root)
            return true;
        queue<TreeNode*> q1;
        queue<TreeNode*> q2;
        q1.push(root->left);
        q2.push(root->right);
        while (!q1.empty() && !q2.empty()){
            TreeNode* node1 = q1.front();
            TreeNode* node2 = q2.front();
            q1.pop(); q2.pop();
            if (!node1 && !node2) continue;
            if (!node1 || !node2 || node1->val != node2->val)
                return false;
            q1.push(node1->left);
            q1.push(node1->right);
            q2.push(node2->right);
            q2.push(node2->left);
        }
        return true;
    }
    
};

 

Posted by bazza84 on Mon, 07 Oct 2019 18:00:14 -0700