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.
题目判断两个binary tree是否相等。
使用dfs。一旦遇到不相等的节点,就跳出dfs,该节点的所有子节点以及它的兄弟节点(右节点)都不用再遍历了。算是一种剪枝吧。
其中用到&&的隐含作用。dfs(p->left, q->left) && dfs(p->right, q->right)
当&&前面的表达式为flase时,整体表达式肯定为false。&&后面的直接忽略不计算了。
class Solution {
public:
bool isSameTree(TreeNode* p, TreeNode* q) {
return dfs(p, q);
}
bool dfs(TreeNode* p, TreeNode* q){
if(p==NULL&&q==NULL)
return true;
else if(p!=NULL&&q!=NULL&&p->val==q->val){//当前节点相等
return dfs(p->left, q->left) && dfs(p->right, q->right);//再判断左右子树是否相等。这里&&的隐含作用是左子树为false时,右子树就不用再搜了
//if(!dfs(p->left, q->left)) return false; //&&的作用等价于这两句。
//else return dfs(p->right, q->right);
}
else
return false;//当不满足条件时,返回false,该节点的所有子节点都不用再遍历了
}
};