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
Note:
Bonus points if you could solve it both recursively and iteratively.
confused what "{1,#,2,3}"
means? > read more on how binary tree is serialized on OJ.
递归实现方法:
/** * 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* root) { if (!root || (!root->left && !root->right)) { return true; } bool rt = doJudge(root->left, root->right); return rt; } bool doJudge(TreeNode* lr, TreeNode *rr) { if ((lr == NULL && rr == NULL)) { return true; } if ((lr && !rr) || (!lr && rr) ) { return false; } if (lr->val != rr->val) { return false; } bool check1 = doJudge(lr->left, rr->right); bool check2 = doJudge(lr->right, rr->left); return (check1 && check2); } };