相同,对称二叉树递归和非递归解法
一、首先看相同二叉树(判断二叉树是否相同)
1.递归
递归解法比较简单:
1.首先判断根的情况。
2.递归判断左右子树。
代码:
bool isSameTree(TreeNode* p, TreeNode* q) {
if((p == NULL && q != NULL) || (p != NULL && q == NULL)) return false;
if(q == NULL && q == NULL) return true;
if(q->val != p->val) return false;
else {
bool tmp1 = isSameTree(p->left,q->left);
bool tmp2 = isSameTree(p->right,q->right);
if(!tmp1 || !tmp2) return false;
}
return true;
}
2.非递归
非递归的主要的思路是:用一个队列来储存两个树相同位置的结点。循环取出两个结点,检查是不是相同,不同就return false
,如果相同就把取出的两个节点的左右子树入队。
1.把两个树根结点入队。
2.取出队列中的两个节点,检查是不是相同。
3.把取出的两个节点的左右子树入队。
4.重复2,3直到对列空。
bool isSameTree(TreeNode* p, TreeNode* q) {
queue<TreeNode*> que;
que.push(p);
que.push(q);
while(!que.empty()){ //迭代
auto tmp1 = que.front(); que.pop();
auto tmp2 = que.front(); que.pop();
//检查部分
if(tmp1 == NULL && tmp2 == NULL) continue;
if(tmp1 == NULL || tmp2 == NULL) return false;
if(tmp1->val != tmp2->val) return false;
que.push(tmp1->left);
que.push(tmp2->left);
que.push(tmp1->right);
que.push(tmp2->right);
}
return true;
}
二、对称二叉树(判断二叉树是否镜像对称)
其实这个问题的答案和判断是不是相同的答案基本上是一样的。
只需套把代码中的left
改成right
,把right
改成left
,然后稍微调整一下就行了。
1.递归
bool isSymmetric(TreeNode* root) {
bool tmp;
if(root == NULL) return true;
tmp = isSymmetricTree(root->left,root->right);
return tmp;
}
bool isSymmetricTree(TreeNode* p, TreeNode* q) {
if(p == NULL && q == NULL) return true;
if((p == NULL && q != NULL) || (p != NULL && q == NULL)) return false;
if(p->val != q->val) return false;
else {
bool tmp1 = isSymmetricTree(p->left,q->right);
bool tmp2 = isSymmetricTree(p->right,q->left);
if(!tmp1 || !tmp2) return false;
}
return true;
}
2.非递归
bool isSymmetric(TreeNode* root) {
queue<TreeNode*> q;
q.push(root);
q.push(root);
while(!q.empty()){
auto tmp1 = q.front(); q.pop();
auto tmp2 = q.front(); q.pop();
if(tmp1 == NULL && tmp2 == NULL) continue;
if(tmp1 == NULL || tmp2 == NULL) return false;
if(tmp1->val != tmp2->val) return false;
q.push(tmp1->left);
q.push(tmp2->right);
q.push(tmp1->right);
q.push(tmp2->left);
}
return true;
}