相同,對稱二叉樹遞歸和非遞歸解法
一、首先看相同二叉樹(判斷二叉樹是否相同)
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;
}