LeetCode-101. Symmetric Tree-using C

【题目描述】

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

For example, this binary tree [1,2,2,3,4,4,3] is symmetric:

    1
   / \
  2   2
 / \ / \
3  4 4  3

But the following [1,2,2,null,3,null,3] is not:

    1
   / \
  2   2
   \   \
   3    3

即判断一棵二叉树是否是对称的

【函数形式】

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
bool isSymmetric(struct TreeNode* root) {

}

【解题思路】

左子树为空,右子树也为空,或者,左子树与右子树的value相等时,以根节点为根的二叉树是对称的。那么我们可以设计这样一个函数,传入两个指向树节点的指针,判断两个指针所指向的结点是否对称,从根节点开始递归调用该函数。

【代码如下】

bool function(struct TreeNode* left, struct TreeNode* right);
bool isSymmetric(struct TreeNode* root) {
    return function(root,root);
}
bool function(struct TreeNode* left, struct TreeNode* right)
{
    if(left == NULL && right == NULL)
        return 1;
    if (left->val != right->val)
	    return 0;
    if(left == NULL && right != NULL)
        return 0;
    if(left != NULL && right == NULL)
        return 0;

    int r1,r2;

    if(left->left != NULL && right->right != NULL)
    {
        r1 = function( (left->left), (right->right));
    }
    else if (left->left == NULL && right->right == NULL)
    {
        r1 = 1;
    }
    else
    {
        return 0;
    }

    if (left == right)
    {
        //root 
        return r1;
    }


    if(right->left != NULL && left->right != NULL)
    {
        r2 = function( (left->right), (right->left));
    }
    else if (right->left == NULL && left->right == NULL)
    {
        r2 = 1;
    }
    else
    {
        return 0;
    }


    return r1&&r2;
}

猜你喜欢

转载自blog.csdn.net/weixin_32549789/article/details/79567245
今日推荐