872.Leaf Similar Trees

Last updated

Last updated
/**
* 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 {
private:
vector<int> r;
string leaf(TreeNode* root)
{
string res;
if(! root) return res;
if(root->left)
res+=leaf(root->left);
if(root->right)
res+=leaf(root->right);
if(!root->left && !root->right)
res+= " "+ to_string(root->val);
return res;
}
public:
bool leafSimilar(TreeNode* root1, TreeNode* root2) {
// cout<< leaf(root1)<<endl;
// cout<< leaf(root2)<<endl;
return leaf(root1) == leaf(root2);
}
};