题目描述(Easy)
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
题目链接
https://leetcode.com/problems/same-tree/description/
Example 1:
For example, this binary tree [1,2,2,3,4,4,3] is symmetric:
1
/ \
2 2
/ \ / \
3 4 4 3
Example 2:
But the following [1,2,2,null,3,null,3] is not:
1
/ \
2 2
\ \
3 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* root) {
return compare(root, root);
}
private:
bool compare(TreeNode* p, TreeNode* q)
{
if (p == NULL && q == NULL) return true;
if (p == NULL || q == NULL) return false;
return p->val == q->val
&& compare(p->left, q->right)
&& compare(p->right, q->left);
}
};