My accepted C++ iterative solution within 40ms


  • 0
    V
    class Solution {
    public:
        bool isSymmetric(TreeNode *root) {
            if (root == NULL) return true;
            
            vector<TreeNode *> vec;
            vec.push_back(root);
            
            vector<TreeNode *> tmp;
            while (true) {
                for (vector<TreeNode *>::iterator iter = vec.begin(), riter = vec.end() - 1;
                     iter <= riter; ++iter, --riter) {
                    if (*iter != NULL && *riter != NULL) {
                        if ((*iter)->val != (*riter)->val) {
                            return false;
                        }
                    } else {
                        if (*iter != *riter) {
                            return false;
                        }
                    }
                }
                
                for (vector<TreeNode *>::iterator iter = vec.begin(); iter != vec.end(); ++iter) {
                    if (*iter != NULL) {
                        tmp.push_back((*iter)->left);
                        tmp.push_back((*iter)->right);
                    }
                }
                
                vec = tmp;
                if (tmp.empty()) return true;
                else tmp.clear();
            }
        }
    };

Log in to reply
 

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