题解 | 在二叉树中找到两个节点的最近公共祖先
在二叉树中找到两个节点的最近公共祖先
https://www.nowcoder.com/practice/e0cc33a83afe4530bcec46eba3325116
/** * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * }; */ class Solution { public: int flag = 0; int lowestCommonAncestor(TreeNode* root, int o1, int o2) { vector<int> path1, path2; dfs(root, path1, o1); flag = 0; dfs(root, path2, o2); int res = 0; for(int i=0; i<path1.size() && i<path2.size(); i++){ if(path1[i] == path2[i]){ //共同祖先的之前的路径是相同的 res = path1[i]; }else{ break; } } return res; } void dfs(TreeNode* root,vector<int>& path, int target){ if(root==nullptr){ return; } if(root->val == target){ path.push_back(root->val); //自己也可能是根节点,添加进去检测 flag = 1; return; } path.push_back(root->val); dfs(root->left, path, target); if(flag == 1){ return; } dfs(root->right, path, target); if( flag == 1 ){ return; } path.pop_back(); return; } };