C++ Clean Recursion Code without Helper in 3ms


  • 0
    M
    /**
     * 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;
            
            TreeNode * left = root->left;
            TreeNode * right = root->right;
            
            if(!left && !right) return true;
            if ((!left && right) || (left && !right)) return false;
            
            bool t = true;
            
            if (root->left->val == root->right->val) {
                root->left = left->left;
                root->right = right->right;
                t = t && isSymmetric(root);
                root->left = left->right;
                root->right = right->left;
                t = t && isSymmetric(root);
            } else {
                return false;
            }
            
            return t;
        }
    };
    

Log in to reply
 

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