LeetCode 100. Same Tree 题解(C++)
题目描述
- 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.
思路
- 使用递归实现。首先先判断两个结点是否同时为空,是的话则返回true,若一个结点为空,另一个结点为非空,则返回false;
- 再判断两个结点的值是否相等,若不等则返回false;
- 之后分别对左右子树进行递归,分别判断左右子树是否一样(这里的一样指的是形状相识,对应结点值相等),并返回左右子树返回的bool值的逻辑与。
代码
/**
* Definition for a binary tree node.
* 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 p == q;
}
if (p->val != q->val)
{
return false;
}
bool isSameLeftTree = isSameTree(p->left, q->left);
bool isSameRightTree = isSameTree(p->right, q->right);
return isSameLeftTree && isSameRightTree;
}
};