Consider all the leaves of a binary tree. From left to right order, the values of those leaves form a leaf value sequence.
For example, in the given tree above, the leaf value sequence is (6, 7, 4, 9, 8).
Two binary trees are considered leaf-similar if their leaf value sequence is the same.
Return true if and only if the two given trees with head nodes root1 and root2 are leaf-similar.
Constraints:
Both of the given trees will have between 1 and 200 nodes.
Both of the given trees will have values between 0 and 200
这题很简单,检查两个树的叶子节点的值是否一致。直接用先序遍历就可以得到所有叶子节点的值。
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:
bool leafSimilar(TreeNode* root1, TreeNode* root2) {
vector<int> lv;
vector<int> rv;
lvs(root1, lv);
lvs(root2, rv);
return lv == rv;
}
void lvs(TreeNode *root, vector<int> &res) {
if (root->left == nullptr && root->right == nullptr) {
res.push_back(root->val);
return;
}
if (nullptr != root->left) {
lvs(root->left, res);
}
if (nullptr != root->right) {
lvs(root->right, res);
}
}
};