LeetCode题解——叶子相似的树
- 题目介绍
- 解题思路
- 前序遍历二叉树,将叶子节点保存下来
- 比较2个二叉树的叶子节点
- 代码示例
/**
* Definition for a binary tree node.
* 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:
void Traversal(TreeNode* root,vector<int> &tree){
if(root->left == NULL && root->right == NULL) {
tree.push_back(root->val);
return;
}
if(root->left != NULL) {
Traversal(root->left,tree);
}
if(root->right != NULL) {
Traversal(root->right,tree);
}
return;
}
bool tcompare(vector<int>tree1, vector<int>tree2) {
int len = tree1.size();
for(int i = 0; i<len; i++) {
if(tree1[i] != tree2[i]) {
return false;
}
}
return true;
}
bool leafSimilar(TreeNode* root1, TreeNode* root2) {
vector<int> tree1,tree2;
Traversal(root1,tree1);
Traversal(root2,tree2);
if(tree1.size() != tree2.size()) {
return false;
}
return tcompare(tree1,tree2);
}
};