问题:https://leetcode.com/problems/same-tree/?tab=Description
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.
给两个二叉树,写一个函数判断它们是否相等。相等是指拥有相同的结构以及节点的值一一对应相等。
分析:数据结构题目。这两棵二叉树同步地遍历,当遍历过程中出现不同步则肯定不相等,能遍历结束则相等。
参考C++代码:
/**
* 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(NULL==p && NULL==q) return true;
if(NULL==p || NULL==q || p->val != q->val || !isSameTree(p->left,q->left)|| !isSameTree(p->right,q->right)) return false;
return true;
}
};