题目
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 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) {
vector<int> p1,p2,p3,q1,q2,q3;
DFS(p,p1,p2,p3);
DFS(q,q1,q2,q3);
return (p1==q1)&&(p2==q2)&&(p3==q3);
}
void DFS(TreeNode* root, vector<int>& result1,vector<int>& result2,vector<int>& result3) {
if(root==NULL) { //记录空节点
result1.push_back(-11);
result2.push_back(-11);
result3.push_back(-11);
return;
}
result1.push_back(root->val); //前序
DFS(root->left,result1,result2,result3);
result2.push_back(root->val); //中序
DFS(root->right,result1,result2,result3);
result3.push_back(root->val); //后序
}
};