[LeetCode]101. Symmetric Tree

1449 단어
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

귀속 방식을 채택하다
#include 
#include 

struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
};

int isAMirror(struct TreeNode *left, struct TreeNode *right) {
    if(left==NULL && right==NULL)
        return 1;
    if(left==NULL || right==NULL)
        return 0;

    return (left->val == right->val) && isAMirror(left->left, right->right) && isAMirror(left->right, right->left);
}

int isSymmetric(struct TreeNode *root) {
    if(root == NULL)
        return 1;

    return isAMirror(root->left, root->right);
}

int main() {
    struct TreeNode *root = malloc(sizeof(struct TreeNode));
    root->val = 1;

    struct TreeNode *left = malloc(sizeof(struct TreeNode));
    left->val = 2;

    struct TreeNode *right = malloc(sizeof(struct TreeNode));
    right->val = 3;

    root->left = left;
    root->right = right;
    left->left = NULL;
    left->right = NULL;
    right->left = NULL;
    right->right = NULL;

    assert(isSymmetric(root) == 0);

    return 0;
}

좋은 웹페이지 즐겨찾기