标签:des io for 问题 cti ar amp ef
问题描述:
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 binary tree
* 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) {
int flag = 1;/*标识两棵树是否一样*/
_isSameTree_core(p, q, flag);
return flag;
}
void _isSameTree_core(TreeNode *p, TreeNode *q, int &flag) {
if (!p && !q)
return;
else if ((!p && q) || (p && !q) || (p->val != q->val)) {
flag = 0;
return;
} else if (p && q) {
_isSameTree_core(p->left, q->left, flag);
_isSameTree_core(p->right, q->right, flag);
}
}
};标签:des io for 问题 cti ar amp ef
原文地址:http://blog.csdn.net/wan_hust/article/details/38333389