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 a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
bool isTwoSym(struct TreeNode *leftRoot, struct TreeNode *rightRoot)
{
    int leftR, rightR;
    if(leftRoot == NULL && rightRoot == NULL)
        return true;
    else if(leftRoot == NULL && rightRoot != NULL)
        return false;
    else if(leftRoot != NULL && rightRoot == NULL)
        return false;
    else if(leftRoot->val == rightRoot->val)
        {
            leftR = isTwoSym(leftRoot->left, rightRoot->right);
            rightR = isTwoSym(leftRoot->right, rightRoot->left);
            return(leftR && rightR);
        }
    else
        return false;
}

bool isSymmetric(struct TreeNode* root) {
    bool left, right;
    if(root == NULL)
        return true;
    else 
        return isTwoSym(root, root);
}
posted @ 2015-10-15 16:06  dylqt  阅读(147)  评论(0编辑  收藏  举报