sourcecode

Wednesday, January 2, 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 {//recursion
    bool mirrorEqual(TreeNode* r1, TreeNode* r2){
        if (!r1 && !r2) return true;
        if (!r1 || !r2) return false;
        if (r1->val != r2->val) return false;
        return (mirrorEqual(r1->left,r2->right) && mirrorEqual(r1->right, r2->left) );
        
    }
public:
    bool isSymmetric(TreeNode *root) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if (!root) return true;
        return mirrorEqual(root->left, root->right);
    }
}; 
/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {//iteration
    vector<int> v;
    void inOrder(TreeNode* root){
        if (!root) return;
        inOrder(root->left);
        v.push_back(root->val);
        inOrder(root->right);
    }
public:
    bool isSymmetric(TreeNode *root) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if (!root) return true;
        v.clear();
        inOrder(root);
        if (v.size()%2 == 0) return false;//has to be odd
        for(int ii = 0; 2*ii < v.size(); ++ii){
            if (v[ii] != v[v.size()-1-ii]) return false;
        }
        return true;
    }
};

No comments: