题目
解法
简单递归。
C++
/**
* 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 dfs(vector<int>& vec, TreeNode* root) {
if (!root) {
return;
}
if (!root->left && !root->right) {
vec.push_back(root->val);
return;
}
dfs(vec, root->left);
dfs(vec, root->right);
}
bool leafSimilar(TreeNode* root1, TreeNode* root2) {
vector<int> vec1, vec2;
dfs(vec1, root1);
dfs(vec2, root2);
if (vec1.size() != vec2.size()) {
return false;
}
for (int i = 0; i < vec1.size(); i++) {
if (vec1[i] != vec2[i]) {
return false;
}
}
return true;
}
};
JAVA
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean leafSimilar(TreeNode root1, TreeNode root2) {
ArrayList<Integer> list1 = new ArrayList<>();
ArrayList<Integer> list2 = new ArrayList<>();
dfs(list1, root1);
dfs(list2, root2);
return list1.equals(list2);
}
private void dfs(ArrayList<Integer> list, TreeNode root) {
if (root == null) {
return;
}
if (root.left == null && root.right == null) {
list.add(root.val);
}
dfs(list, root.left);
dfs(list, root.right);
}
}