题目意思依然很简单,判断两个二叉树是否相同
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.
二叉树相关的问题大部分都可以用递归的实现来解决,判断每个子树相同即可。
Code 如下:
/*** Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
bool isSameTree(struct TreeNode* p, struct TreeNode* q) {
if (NULL == p && NULL == q)
return true;
if (NULL == p || NULL == q)
return false;
if (p->val != q->val)
return false;
return (isSameTree(p->left,q->left) && isSameTree(p->right,q->right));
}
ps:看到两年前写的代码,实在不忍直视...