越写越不会
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* };
*/
class Solution {
public:
int lowestCommonAncestor(TreeNode* root, int p, int q) {
int res;
std::vector<int> p_path, q_path;
find_path(p_path, root, p);
find_path(q_path, root, q);
for (int i = 0; i < p_path.size() && i < q_path.size(); ++i) {
if (p_path[i] == q_path[i]) {
res = p_path[i];
}
}
return res;
}
private:
void find_path(std::vector<int> &path, TreeNode *root, int target) {
while (root->val != target) {
path.push_back(root->val);
if (root->val > target) {
root = root->left;
} else {
root = root->right;
}
}
// 结点本身也在路径的一部分
path.push_back(root->val);
}
};