现在更新leetcode 主要是提高对c++的熟悉。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
bool isSymmetric(TreeNode* root) {
return ismirror(root, root);
}
bool ismirror(TreeNode* left, TreeNode* right){
if (!left && !right){
return true;
}
if(!left || !right){
return false;
}
if(left->val == right->val){
return ismirror(left->left, right->right) && ismirror(left->right, right->left);
}
return false;
}
};
ismirror(1,1)
ismirror(2,2)
ismirror(3,3) and ismirror(4,4)
如果在增加一层[5,6,6,7,7,6,6,5]
ismirror(5,5) ismirror(6,6) …
使用非递归,需要注意:
先天加 left->left, right->right, left->right 和 right->left, 并不是顺序的从左到右的添加。
成对的添加到队列和出队列。
c++ tips:
注意:把一个完整的结构体变量作为参数传递,要将全部成员值一个一个传递,费时间又费空间,开销大。如果结构体类型中的成员很多,或有一些成员是数组,则程序运行效率会大大降低。在这种情况下,用指针做函数参数比较好,能提高运行效率。
class Solution {
public:
bool check(TreeNode *u, TreeNode *v) {
queue <TreeNode*> q;
q.push(u); q.push(v);
while (!q.empty()) {
u = q.front(); q.pop();
v = q.front(); q.pop();
if (!u && !v) continue;
if ((!u || !v) || (u->val != v->val)) return false;
q.push(u->left);
q.push(v->right);
q.push(u->right);
q.push(v->left);
}
return true;
}
bool isSymmetric(TreeNode* root) {
return check(root, root);
}
};
参考:
https://www.cnblogs.com/spring-hailong/p/6106687.html
https://leetcode-cn.com/problems/symmetric-tree/solution/dui-cheng-er-cha-shu-by-leetcode-solution/