使用递归应该是最简单的解法了:
运行时间 3ms,内存占用 424 KB
class Solution {
public:
bool judge(TreeNode* a, TreeNode*b){
if(a==b) return true;
if(!a) return false;
if(!b) return false;
return a->val==b->val && judge(a->right, b->left)&&judge(a->left, b->right);
}
bool isSymmetric(TreeNode* root) {
// write code here
if(!root) return true;
return judge(root->left, root->right);
}
}; 感觉代码写的比第一名写的还简洁,为什么运行速度要 3ms 呢。拿来第一名的代码跑,也是要 3ms,大概是服务器的问题吧

京公网安备 11010502036488号