/** * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * }; */ #include <vector> class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param root TreeNode类 * @param o1 int整型 * @param o2 int整型 * @return int整型 */ bool flag = false; int lowestCommonAncestor(TreeNode* root, int o1, int o2) { // write code here vector<TreeNode*> path1; dfs(root,path1,o1); flag = false; vector<TreeNode*> path2; dfs(root,path2,o2); int res = 0; for(int i=0;i<path1.size()&&i<path2.size();i++){ if(path1[i]->val==path2[i]->val) res = path1[i]->val; else break; } return res; } void dfs(TreeNode* root, vector<TreeNode*>& path, int o){ if(flag || !root) return ; path.push_back(root); if(root->val == o){ flag = true; return ; } dfs(root->left, path, o); dfs(root->right, path, o); if(flag) return ; else path.pop_back(); } };
dfs先序遍历,在遍历的过程中把路径和标识带上,通过标识flag确定如何保留路径。最后再进行两个路径的比较。