問題描述:
檢查兩棵二叉樹是否等價。等價的意思是說,首先兩棵二叉樹必須擁有相同的結構,並且每個對應位置上的節點上的數都相等。
樣例
1 1
/ \ / \
2 2 and 2 2
/ /
4 4
就是兩棵等價的二叉樹。
1 1
/ \ / \
2 3 and 2 3
/ \
4 4
就不是等價的。
首先判斷特殊情況,對空二叉樹的情況驚醒判斷;當兩個二叉樹都不是空的時,比較兩者數值是否相等,在判斷左右子樹位置等。
代碼:
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @aaram a, b, the root of binary trees.
* @return true if they are identical, or false.
*/
bool isIdentical(TreeNode* a, TreeNode* b) {
if(a==NULL&&b==NULL) return true;
if((a!=NULL&&b==NULL)||(a==NULL&&b!=NULL)) return false;
if(a->val==b->val)
{
return isIdentical(a->left,b->left)&&isIdentical(a->right,b->right);
}
else return false;
// Write your code here
}
};
感悟:
在做題時沒有考慮數值問題,後在對之進行比較時出錯。