LeetCode 101 Symmetric Tree
看越来越多paper之后发现数据结构真的很重要,很多厉害的paper都在利用各种数据结构进行花式效果优化,刚好博客园有个叫学习计划的list(https://academy.cnblogs.com/schedules/doing),闲着没事就刷刷力扣吧😄
今天刷的是力扣101题,关于对称树判断的一个题,看完各种同学的题解思路之后,真的是比刷课本来的生动具体;
题目
题解
递归
基于深度优先搜索,从左到右依次遍历
/**
* 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 == NULL) return true;
return isSymmetric(root->left, root->right);
}
private:
bool isSymmetric(TreeNode* p, TreeNode* q){
if(p==NULL && q==NULL) return true;
if(p==NULL || q==NULL) return false;
return (p->val == q->val) && isSymmetric(p->left, q->right) && isSymmetric(p->right, q->left);
}
};
迭代
基于广度优先,一层一层判断
/**
* 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 == NULL) return true;
queue<TreeNode *> q;
q.push(root->left);
q.push(root->right);
while (!q.empty()) {
TreeNode *l = q.front();
q.pop();
TreeNode *r = q.front();
q.pop();
if (l == NULL && r == NULL) continue;
if (l == NULL || r == NULL) return false;
if (l->val != r->val) return false;
q.push(l->left);
q.push(r->right);
q.push(l->right);
q.push(r->left);
}
return true;
}
};

浙公网安备 33010602011771号