Same Tree
Given two binary trees, write a function tocheck if they are equal or not.
Two binary trees are considered equal ifthey 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(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;
}
};