1、題目
Given two binary trees, write a function to check if they are equal or not.
Two binary trees are considered equal if they are structurally identical and the nodes have the same value.
2、分析
判斷兩棵樹是否相同,最直接的方法是用遞歸,假設兩棵樹的根節點分別是p、q,則它們相同的前提是p和q的值相同,並且它們的左右子樹也分別相同,顯然對左右子樹可以遞歸地調用原函數。
運用迭代法的話,只需要維護一個棧,如果p、q的值相同,則依次將p->left,q->left ,p->right,q->right入棧,然后下一次循環開始時,就判斷棧頂的p->right和q->right的值是否相同,相同的話,再把它們的左右孩子依次入棧,循環以上過程,直到碰到值不相等或者棧為空。【迭代法的算法流程可參考下面圖解】
(本題注意:兩個空樹是相等的)
3、代碼
#遞歸版
<span style="font-size:18px;">/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isSameTree(TreeNode *p, TreeNode *q) {
if (!p && !q) return true;
return (p && q && (p->val==q->val) &&isSameTree(p->left,q->left) && isSameTree(p->right,q->right));
}
};</span>
#迭代版
class Solution {
public:
bool isSameTree(TreeNode *p, TreeNode *q) {
stack<TreeNode *> s;
s.push(p);
s.push(q); //即使是空節點,也是可以push到棧里的,棧並不為空。
while(!s.empty())
{
p=s.top();s.pop();
q=s.top();s.pop();
if(!p && !q) continue; //p、q都是空節點
if(!p || !q) return false; //有一個為空,不相等
if(p->val!=q->val) return false; //值不相等
s.push(p->left);s.push(q->left);
s.push(p->right);s.push(q->right);
}
return true;
}
};
---------------------
作者:wepon_
來源:CSDN
原文:https://blog.csdn.net/u012162613/article/details/41212315
版權聲明:本文為博主原創文章,轉載請附上博文鏈接!