[recursive & non-recursive]8 lines concise & clean C++ implementation with detailed explaination


  • 1

    At the first glance, I just want to in-order-traverse the linked list
    , but I find a much more concise solution. We just need to flip the
    sub-tree in the right way.

       Recursive Solution
    
    class Solution {
    public:
        bool isSymmetric(TreeNode* root) {
            if(!root)   return true;
            return help(root->left, root->right);
        }
        bool help(TreeNode* left, TreeNode* right){
            if(left==NULL && right==NULL)   return true;
            if(left==NULL || right==NULL)   return false;
            if(left->val!=right->val)    return false;
            else{
                /***   the key point is the make sure the sub-tree pair relationship  ***/
                return help(left->left, right->right) && help(left->right, right->left);
            }
        }
    };
    
       NON-Recursive Solution
    
    class Solution {
    public:
        bool isSymmetric(TreeNode* root) {
            if(!root)   return true;
            queue<TreeNode*> check;
            
            check.push(root->left);
            check.push(root->right);
            
            while(!check.empty()){
                TreeNode* node1=check.front();
                check.pop();
                TreeNode* node2=check.front();
                check.pop();
                if(!node1 && node2) return false;
                if(node1 && !node2) return false;
                if(node1 && node2){
                    if(node1->val != node2->val)    return false;
                    check.push(node1->left);
                    check.push(node2->right);
                    check.push(node1->right);
                    check.push(node2->left);
                }
            }
            return true;
        }
    };

  • 0
    class Solution {
    public:
        bool isSymmetric(TreeNode* root) {
            if(!root)  return true;
            return help(root->left, root->right);
        }
        
        bool help(TreeNode *left, TreeNode *right){
            if(!left && !right) return true;
            else if(!left || !right) return false;
            else if(left->val !=  right->val)  return false;
            else return help(left->left, right->right) && help(left->right, right->left);
        }
    };

Log in to reply
 

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