《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
Note:
Bonus points if you could solve it both recursively and iteratively.

思路

将左子树的左节点的值与右子树的右节点的值进行比较,而将左子树的右节点的值与右子树的左节点的值进行比较即可。

实现代码如下:

/** * Definition for a binary tree node. * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */

bool isSym(struct TreeNode* leftroot,struct TreeNode* rightroot){
    if(leftroot==NULL&&rightroot==NULL){
        return true;
    }
    else if(leftroot==NULL&&rightroot!=NULL||(leftroot!=NULL&&rightroot==NULL)) {
        return false;
    }

    return (leftroot->val==rightroot->val)&&isSym(leftroot->left,rightroot->right)&&isSym(leftroot->right,rightroot->left);
}
bool isSymmetric(struct TreeNode* root) {
    return isSym(root,root) ; 
}

你可能感兴趣的:(LeetCode,tree,Symmetric)