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; } };