题解 | #相逆叶子#
相逆叶子
https://www.nowcoder.com/practice/41c7b0e8710e43ca9f328bf06ea2aff3
/** * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * }; */ #include <iterator> #include <vector> class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param root1 TreeNode类 * @param root2 TreeNode类 * @return bool布尔型 */ bool leafSimilar(TreeNode* root1, TreeNode* root2) { vector<int> l1, l2; function<void(TreeNode*, vector<int>&)> dfs = [&](TreeNode * root, vector<int>&l) -> void{ if(root == nullptr) return; if(root->left == nullptr && root->right == nullptr) l.push_back(root->val); dfs(root->left, l); dfs(root->right, l); }; /** 一直比较直观的方法是实用 BFS 搜索最后一层, 不过其实深搜前序遍历同样可以搜集叶子节点 收集之后 vector 其实可以直接比较, l1 和 l2 随便挑选一个翻转然后比较比较即可 */ dfs(root1, l1); dfs(root2, l2); reverse(l2.begin(), l2.end()); return l1 == l2; } };
`