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.
直接DFS,递归调用判断就好,注意边界和递归返回即可。
/**
* 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(NULL==p && NULL==q)
return true;
else if(NULL!=p&&NULL!=q)
{
if(p->val!=q->val)
return false;
else
return isSameTree(p->left,q->left)&&isSameTree(p->right,q->right);
}
else
return false;
}
};
本文介绍了一种通过深度优先搜索(DFS)递归方法来判断两个二叉树是否等价的有效算法。当两棵树在结构上完全相同且对应节点的值也相等时,它们被认为是等价的。该方法首先检查根节点是否都为空或者都不为空,并在此基础上进一步比较左右子树。
1418

被折叠的 条评论
为什么被折叠?



