码迷,mamicode.com
首页 > 其他好文 > 详细

Symmetric Tree

时间:2015-10-15 18:28:53      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:

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);
}

Symmetric Tree

标签:

原文地址:http://www.cnblogs.com/dylqt/p/4882696.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!