力扣872.-叶子相似的树
目录
力扣872. 叶子相似的树
/**
* 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:
void leafcnt(TreeNode* root,vector<int>& ans)
{
if(root==nullptr)
{
return;
}
else
{
leafcnt(root->left,ans);
if(root->left==nullptr&&root->right==nullptr)
ans.push_back(root->val);
leafcnt(root->right,ans);
}
}
bool leafSimilar(TreeNode* root1, TreeNode* root2) {
vector<int> ans1;
vector<int> ans2;
leafcnt(root1,ans1);
leafcnt(root2,ans2);
if(ans1==ans2)
{
return true;
}
else{
return false;
}
}
};
时间复杂度O(n)