Description:
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.
Note:
無
Solution:
Analysis and Thinking:
題目要求在給定兩棵樹的情況下,判斷這兩棵樹是否相等,可以使用遞歸的方式實現
Steps:
1. 判斷當前兩節點是否有任一爲空,如果有,表示不相等,返回false
2. 如果當前兩節點都爲空,表示兩棵樹都已經遍歷完畢,所有節點都相等,返回true
3. 如果兩節點都非空,比較節點的值,如果不等,返回false
4. 遞歸對兩節點的左子樹以及右子樹調用1~3步
Codes:
class Solution {
public:
bool isSameTree(TreeNode *p, TreeNode *q) {
if(p && !q)
return false;
else if(!p && q)
return false;
else if(!p && !q)
return true;
else
{
if(p->val != q->val)
return false;
else
return isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
}
}
};
Results: