
思路:
利用一个help函数,将一颗二叉树上的所有叶子节点的值按从左向右的顺序保存到vector中。
那么将root1的叶子节点的值保存到vec1中,root2保存到vec2中。假如vec1和vec2长度不一样,返回false。假如一样,比较两个数组相同下标对应的值是否相等,假如有不相等,返回false,否则返回true。
这里自己遇到的一个问题,help函数中,假如遇到空节点需要return,因为下面的递归有用到root->left和root->right,而空节点的root->left和root->right则没有,因此报错。所以以后有用到root->left和root->right的地方,一定要保证root不为空。
执行出错:

解题代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
bool leafSimilar(TreeNode* root1, TreeNode* root2) {
if(!root1&&!root2)
return true;
vector<int>vec1,vec2;
help(vec1,root1);
help(vec2,root2);
int len1=vec1.size(),len2=vec2.size();
if(len1!=len2)
return false;
for(int i=0;i<len1;++i){
if(vec1[i]!=vec2[i])
return false;
}
return true;
}
void help(vector<int> &vec,TreeNode* root){
//这里注意,必须要根节点root不等于空,才可以用root->left和root->right,否则就会报错
//其实也就是要考虑终止条件,因为这里用到了递归的方法
if(!root)
return;
if(!root->left&&!root->right)
vec.push_back(root->val);
help(vec,root->left);
help(vec,root->right);
}
};
472

被折叠的 条评论
为什么被折叠?



