101. Symmetric Tree

    xiaoxiao2021-11-30  33

    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

    思路:對稱樹就是 左 中 右 和 右 中 左 都是一樣的。

    class Solution { public: bool isSymmetric(TreeNode* root) { if (root == NULL || (root->left == NULL && root->right == NULL)) { return true; } return check(root->left, root->right); } bool check(TreeNode *leftChild, TreeNode *rightChild) { if (leftChild != NULL && rightChild != NULL) { return (leftChild->val == rightChild->val) && check(leftChild->left, rightChild->right) && check(leftChild->right, rightChild->left); } return leftChild == rightChild; } };

    转载请注明原文地址: https://ju.6miu.com/read-679039.html

    最新回复(0)