题目:
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.
题意:
给出两个二叉树,判断两棵树是否相等
解题思路:
1、两树是否为空(共有四种情况,两者都空【1】,一个为空【2】,两个都不为空【1】),前三种情况很好判断,重点在第四种情况
2、两树均不为空:
判断两个数是否相等,很容易想到用深度遍历DFS进行递归求解
1)左右子树是否相等
2)树节点的value值是否相等
只有当以上两个条件均满足时,才可判断两个树相等
代码:
/**
* 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==NULL&&q==NULL)
return true;
if(p!=NULL&&q==NULL)
return false;
if(p==NULL&&q!=NULL)
return false;
if(isSameTree(p->left,q->left) && isSameTree(p->right,q->right))
if(p->val==q->val)
return true;
return false;
}
};