leetcode 101. 对称二叉树(Symmetric Tree)

题目描述:

给定一个二叉树,检查它是否是镜像对称的。

例如,二叉树 [1,2,2,3,4,4,3] 是对称的。

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

但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的:

        1
       / \
      2   2
       \   \
       3    3

说明:

  • 如果你可以运用递归和迭代两种方法解决这个问题,会很加分。

解法:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool isSymmetric(TreeNode* l, TreeNode* r){
        if(l == NULL && r == NULL){
            return true;
        }else if(l == NULL || r == NULL || l->val != r->val){
            return false;
        }else{
            return isSymmetric(l->left, r->right) && isSymmetric(l->right, r->left);
        }
    }
    
    bool isSymmetric(TreeNode* root) {
        if(root == NULL){
            return true;
        }else{
            return isSymmetric(root->left, root->right);
        }
    }
};

猜你喜欢

转载自www.cnblogs.com/zhanzq/p/10556948.html