请考虑一颗二叉树上所有的叶子,这些叶子的值按从左到右的顺序排列形成一个叶值序列 。
举个例子,如上图所示,给定一颗叶值序列为 (6, 7, 4, 9, 8) 的树。
如果有两颗二叉树的叶值序列是相同,那么我们就认为它们是叶相似的。
如果给定的两个头结点分别为 root1 和 root2 的树是叶相似的,则返回 true;否则返回 false
样例
样例 1:
输入: {1,#,2,3}, {1,2,#,3}
输出: true
解释:
第一棵树:
1
\
2
/
3
第二棵树:
1
/
2
/
3
叶值序列都为:[3],所以相同
样例 2:
输入: {1,#,2,3}, {1,2,3}
输出: false
解释:
第一棵树:
1
\
2
/
3
第二棵树:
1
/ \
2 3
第一棵树叶值序列都:[3],第二个树为:[2, 3],所以不相同
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root1: the first tree
* @param root2: the second tree
* @return: returns whether the leaf sequence is the same
*/
bool leafSimilar(TreeNode * root1, TreeNode * root2) {
// write your code here.
recursion(root1,tmp1);
recursion(root2,tmp2);
if(tmp1.size()!=tmp2.size()) return false;
for (int i = 0; i < tmp1.size(); i++) {
/* code */
if(tmp1[i]!=tmp2[i]) return false;
}
return true;
}
void recursion(TreeNode * root,vector<int> &tmp)
{
if(root->left==NULL&&root->right==NULL){tmp.push_back(root->val);return;}
if(root->left)recursion(root->left,tmp);
if(root->right)recursion(root->right,tmp);
}
private:vector<int> tmp1;
vector<int> tmp2;
};