看到题目第一时间想到递归,但苦于在一棵树上怎样实现左右子树但比较。
后来看了官方题解,发现使用两个参数,相当于独立比较两棵树,实现起来也很简洁。
链接 https://leetcode-cn.com/problems/symmetric-tree/solution/dui-cheng-er-cha-shu-by-leetcode/
/**
* 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 comp(root, root);
}
bool comp(TreeNode* r1, TreeNode* r2){
if(r1 == NULL && r2 == NULL) return 1;
if(r1 == NULL || r2 == NULL) return 0;
return (r1->val == r2->val)
&& comp(r1->left, r2->right)
&& comp(r1->right, r2->left);
}
};