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.
不用给也知道吧。。。
没有明确给出。
题目其实很简单,就是分别比较两棵树的结构跟对应节点的值是否一致。注意一下细节就行,节点相同的情况包括两个树对应的指针都是空和两个树的指针都不为空且值相等两种情况。
我是用BFS写的,从头到尾遍历两棵树,对比每个节点就行。代码写得很直观,看一遍就能理解。
这道题目也可以用递归来做。
上面也说了就是对于每一对相应的节点,判断它们是否满足两个指针都是空或两个指针都不为空且值相等中的一个条件。递归的结束条件是指针都是空。简单的2行代码可以搞定。
/** * 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) {
queue<TreeNode*> nodes;
if (!p && p == q) {
return true;
}
nodes.push(p);
nodes.push(q);
while (!nodes.empty()) {
TreeNode *a = nodes.front();
nodes.pop();
TreeNode *b = nodes.front();
nodes.pop();
if ((!a && b) || (a && !b))
return false;
if (a && b) {
if (a->val != b->val)
return false;
nodes.push(a->left);
nodes.push(b->left);
nodes.push(a->right);
nodes.push(b->right);
}
}
return true;
}
};
/** * 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 || !q) return p == q;
return (p->val == q->val) && isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
}
};
这道关于树的题目解法很直观,只要考虑清楚判断条件和判断情况即可。
这是昨天做的题目,但是懒,没有在昨天发,在深刻反省中。。。
今天已经填了两个坑,所以还会有另外两道题的解题报告。加油加油!不能松懈。