leetcode: 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

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {

void visitSubTree(TreeNode *root, bool isLeftTree, vector<int> &curVector)
{
    
    if (!root)
        return;
    
    if (isLeftTree)
    {
        visitSubTree(root->left, isLeftTree, curVector);
        curVector.push_back(root->val);
        visitSubTree(root->right, isLeftTree, curVector);
    }
    else
    {
        visitSubTree(root->right, isLeftTree, curVector);
        curVector.push_back(root->val);
        visitSubTree(root->left, isLeftTree, curVector);        
    }
}
    
public:
    bool isSymmetric(TreeNode *root) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        
        if (!root)
            return true;
            
        vector<int> leftVector;
        vector<int> rightVector;
        
        visitSubTree(root->left, true, leftVector);
        visitSubTree(root->right, false, rightVector);
        
        int leftSize = leftVector.size();
        int rightSize = rightVector.size();
        
        if (leftSize != rightSize)
            return false;
            
        int idx = 0;
        
        while (idx < leftSize)
        {
            if (leftVector[idx] == rightVector[idx])
            {
                idx++;
            }
            else
            {
                return false;
            }
        }
        
        return true;  
    }
};



另外一种解法,转自http://blog.csdn.net/xudli/article/details/8427025

/**
 * 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 isSymRec(TreeNode *left, TreeNode * right){
        if(left == NULL && right==NULL){
            return true;
        } else if(left == NULL || right == NULL) {
            return false;
        }
        
        return ( left->val == right->val && isSymRec( left->left, right->right) && 
            isSymRec( left->right, right->left) );
        //both are not NULL.       
    }

    bool isSymmetric(TreeNode *root) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if(root == NULL) return true;
        return isSymRec( root->left, root->right);
    }
};


你可能感兴趣的:(leetcode: Symmetric Tree)