leetcode 872. Leaf-Similar Trees
题目大意就是判断两棵树的叶子序列是否一样,要考虑顺序。样例:
For example, in the given tree above, the leaf value sequence is (6, 7, 4, 9, 8)
.
思路:
别想复杂了,就是求出每棵树的叶子序列,然后比较就可以了。
求叶子序列我用的是 中序遍历。
AC代码:
/**
* 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:
void inorder(TreeNode* t ,vector<int>& v){
if(t!=NULL){
inorder(t->left,v);
if(t->right==NULL&&t->left==NULL)
v.push_back(t->val);
inorder(t->right,v);
}
}
bool leafSimilar(TreeNode* root1, TreeNode* root2) {
vector<int> v1,v2;
inorder(root1,v1);
inorder(root2,v2);
int l=v1.size(),ll=v2.size();
if(l!=ll)return 0;
for(int i=0;i<l;i++){
if(v1[i]!=v2[i])return 0;
}
return 1;
}
};