算法

2019-10-10  本文已影响0人  西章momo

前言


leetcode上的一些解答,想起来的就写写.

题1


描述

给定一个二叉树,检查它是否是镜像对称的。
例如,二叉树 [1,2,2,3,4,4,3] 是对称的。

1
/ \
2 2
/ \ / \
3 4 4 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* a, TreeNode* b){
        if (a == NULL && b == NULL)
            return true;
        if (a != NULL && b == NULL || a == NULL && b != NULL)
            return false;
        return a->val == b->val && isSymmetric(a->left, b->right) && isSymmetric(a->right, b->left);
    }
    bool isSymmetric(TreeNode* root) {
        if (root == NULL)
            return true;
        return isSymmetric(root->left, root->right);
    }
};
上一篇下一篇

猜你喜欢

热点阅读