没在状态,但还是需要保持一下手感
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
class Solution {
public:
int lowestCommonAncestor(TreeNode* root, int o1, int o2) {
int res;
std::vector<int> o1_path, o2_path;
dfs(root, o1_path, o1);
flag = false;
dfs(root, o2_path, o2);
for (int i = 0; i < o1_path.size() && i < o2_path.size(); ++i) {
if (o1_path[i] == o2_path[i]) {
res = o1_path[i];
}
}
return res;
}
private:
void dfs(TreeNode *root, std::vector<int> &path, int target) {
if (flag || root == nullptr) {
return ;
}
path.push_back(root->val);
if (root->val == target) {
flag = true;
return ;
}
dfs(root->left, path, target);
dfs(root->right, path, target);
if (flag) {
return ;
}
path.pop_back();
}
private:
bool flag = false;
};