先序遍历,遇到叶子节点就push进vector
class Solution {
public:
bool leafSimilar(TreeNode* root1, TreeNode* root2) {
vector<int> leaf1,leaf2;
travel(root1,leaf1);
travel(root2,leaf2);
return leaf1==leaf2;
}
void travel(TreeNode* root,vector<int> &data){
if(root ==NULL)
return;
else if(root->left ==NULL && root->right == NULL)
data.push_back(root->val);
travel(root->left,data);
travel(root->right,data);
}
};