Easy 101. Symmetric Tree
2020-05-03 本文已影响0人
烤肉拌饭多加饭
判断树是否是对称的
方法一:容易想到的递归方法
class Solution {
public:
bool isSymmetric(TreeNode* root) {
return isMirror(root,root);
}
bool isMirror(TreeNode* p, TreeNode* q){
if(p==NULL && q==NULL) return true;
if(p == NULL | q == NULL) return false;
return (p->val == q->val) && isMirror(p->left,q->right)
&& isMirror(p->right,q->left);
}
};
方法二:循环
层序遍历,使用队列
bool isSymmetric(TreeNode* root) {
if(root == NULL) return true;
std::queue<TreeNode*> q;
TreeNode* t1 = new TreeNode();
TreeNode* t2 = new TreeNode();
q.push(root->left);
q.push(root->right);
while(!q.empty()){
t1 = q.front();
q.pop();
t2 = q.front();
q.pop();
if(t1 == NULL && t2 == NULL) continue;
if(t1 == NULL | t2 == NULL) return false;
if(t1->val != t2->val) return false;
q.push(t1->left);
q.push(t2->right);
q.push(t1->right);
q.push(t2->left);
}
return true;
}