Sunday, February 24, 2013

Symmetric Tree

/*
Symmetric Tree
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree is symmetric:
    1
   / \
  2   2
 / \ / \
3  4 4  3

But the following is not:
    1
   / \
  2   2
   \   \
   3    3

Note:
Bonus points if you could solve it both recursively and iteratively.
*/
/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool isSymmetric(TreeNode *root) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if(root==NULL) return true;
        TreeNode *curr = root;
        stack<TreeNode*> s;
        vector<int> num;
        bool reachRoot = false;
        bool isSymetric = true;
        int i = 0;
        int size;
       
        while(curr!=NULL || (!s.empty())){
          if(curr!=NULL){
            s.push(curr);
            curr=curr->left;
          }
          else{
            curr = s.top();
            s.pop();
            if(!reachRoot && curr!=root){
              num.push_back(curr->val);
            }
            if(!reachRoot && curr==root){
              reachRoot = true;
              size = num.size();
            }
            if(reachRoot && curr!=root){
              i++;
              if(size-i<0 || curr->val!=num[size-i]){
               isSymetric = false;
               break;
              }
            }
            curr = curr->right;
          }
        }
       
        if(i!=size){
         isSymetric = false;
        }
       
        return isSymetric;
    }
};

No comments:

Post a Comment