469. 等價二叉樹
檢查兩棵二叉樹是否等價掂恕。等價的意思是說拖陆,首先兩棵二叉樹必須擁有相同的結(jié)構(gòu),并且每個對應位置上的節(jié)點上的數(shù)都相等懊亡。
您在真實的面試中是否遇到過這個題依啰?
Yes
樣例
1 1
/ \ / \
2 2 and 2 2
/ /
4 4
就是兩棵等價的二叉樹。
1 1
/ \ / \
2 3 and 2 3
/ \
4 4
就不是等價的店枣。
相關(guān)題目
AC代碼:
class Solution {
public:
/*
* @param a: the root of binary tree a.
* @param b: the root of binary tree b.
* @return: true if they are identical, or false.
*/
bool isIdentical(TreeNode * a, TreeNode * b) {
// write your code here
if(a==NULL&&b==NULL){
return true;
}
if(a==NULL||b==NULL){
return false;
}
if(a->val!=b->val){
return false;
}
return isIdentical(a->left,b->left)&&isIdentical(a->right,b->right);
}
};