Tuesday, October 7, 2014

Symmetric Tree

//anniekim
class Solution {
public:
    bool isSymmetric(TreeNode *root) {
        return isSymmetric_2(root);
    }
    bool isSymmetric_1(TreeNode *root) {
        if (root == NULL) return true;
        return solve (root->left, root->right);
    }
    bool solve(TreeNode * t1, TreeNode * t2) {
        if (!t1 && !t2) return true;
        if (!t1 && t2 || t1 && !t2 || t1->val != t2->val) return false;
        return solve(t1->left, t2->right) && solve(t1->right, t2->left);
    }
    bool isSymmetric_2(TreeNode *root) {
        if (root == NULL) return true;
        stack<TreeNode *> s;
        s.push(root->left);
        s.push(root->right);
        while (!s.empty()) {
            TreeNode *t2 = s.top(); s.pop();
            TreeNode *t1 = s.top(); s.pop();
            if (!t1 && !t2) continue;
            if (!t1 && t2 || t1 && !t2 || t1->val != t2->val) return false;
            s.push(t1->right);
            s.push(t2->left);
            s.push(t1->left);
            s.push(t2->right);
        }
        return true;
    }
    bool isSymmetric_3(TreeNode *root) {
        if (root == NULL) return true;
        queue<TreeNode *> q;
        q.push(root->left);
        q.push(root->right);
        while (!q.empty()) {
            TreeNode *t1 = q.front(); q.pop();
            TreeNode *t2 = q.front(); q.pop();
            if (!t1 && !t2) continue;
            if (!t1 && t2 || t1 && !t2 || t1->val != t2->val) return false;
            q.push(t1->left);
            q.push(t2->right);
            q.push(t1->right);
            q.push(t2->left);
        }
        return true;
    }
};

//another flavor

    bool isSymmetric(TreeNode *root) {
        if(root==NULL)
            return true;
        stack<TreeNode *> aStack1,aStack2;
        TreeNode *pointer1=root,*pointer2=root;
        while((pointer1&&pointer2)||(!aStack1.empty()&&!aStack2.empty()))
        {
            if(pointer1&&pointer2)
            {
                aStack1.push(pointer1); aStack2.push(pointer2);
                pointer1=pointer1->left;
                pointer2=pointer2->right;
                if((pointer1==NULL&&pointer2)||(pointer2==NULL&&pointer1))
                  return false;
            }
            else{
                pointer1=aStack1.top();aStack1.pop();
                pointer2=aStack2.top();aStack2.pop();
                if(pointer1->val!=pointer2->val)
                    return false;
                pointer1=pointer1->right;
                pointer2=pointer2->left;
                if((pointer1==NULL&&pointer2)||(pointer2==NULL&&pointer1))
                    return false;
            }
        }
        return true;   
    }

No comments:

Post a Comment