A trick based on 100-Same Tree to solve Symmetric Tree in C++

  • 0

    The idea is simple. Reverse the tree and compare the reversal tree with the origin tree.
    If they are same, return true.Otherwise, return false.

    class Solution {
        bool isSymmetric(TreeNode* root) {
            if (root == nullptr) return true;
            ReverseTreeNode *rnode = (ReverseTreeNode*) root;
            return isSame(root, rnode);
        struct ReverseTreeNode {
            int val;
            ReverseTreeNode *right;
            ReverseTreeNode *left;
            ReverseTreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
        bool isSame(TreeNode *node, ReverseTreeNode *rnode) {
            if (node == nullptr && rnode == nullptr) return true;
            if (node == nullptr || rnode == nullptr) return false;
            return node->val == rnode->val
                  && isSame(node->left, rnode->left)
                  && isSame(node->right, rnode->right);

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.