思路:深度遍历以所求节点为终止节点的路径,判断两个路径的交点
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
class Solution {
public:
/**
*
* @param root TreeNode类
* @param o1 int整型
* @param o2 int整型
* @return int整型
*/
int lowestCommonAncestor(TreeNode* root, int o1, int o2) {
// write code here
vector<int> o1_vec;
vector<int> o2_vec;
vector<int> path;
getPath(root, o1, o1_vec,path,0);
path.clear();
getPath(root, o2, o2_vec,path,0);
int path_len = 0;
int result = 0;
if(o1_vec.size()>o2_vec.size()){
path_len = o1_vec.size();
}
else{
path_len = o2_vec.size();
}
for(int i = 0;i<path_len;i++){
if(o1_vec[i] == o2_vec[i]){
result = o1_vec[i];
}
}
return result;
}
private:
void getPath(TreeNode* node,const int target,vector<int> &res,vector<int> &path,int flag){
if(node == NULL || flag == 1){
return ;
}
path.push_back(node->val);
if(node->val == target){
flag = 1;
res = path;
}
getPath(node->left, target, res,path,flag);
getPath(node->right, target, res,path,flag);
path.pop_back();
}
};