[LeetCode] 100.Same Tree
- 题目描述
- 解题思路
- 实验代码
题目描述
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.
解题思路
这道题目比较简单,应用在树中常用的递归操作就能完成。先比较两个树同一节点的情况,看他们是否同时为空,或者同时不为空且节点的值相等,若满足这两种情况则继续查看他们的左子节点和右子节点分别是否是相同的情况,进而得出这两个二叉树是否相同。
实验代码
/**
* 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 true;
if ((p == NULL && q != NULL) || (p != NULL && q == NULL) || (p->val != q->val))
return false;
return isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
}
};