题解 | #在二叉树中找到两个节点的最近公共祖先#
在二叉树中找到两个节点的最近公共祖先
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: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param root TreeNode类 * @param o1 int整型 * @param o2 int整型 * @return int整型 */ vector<int> path1; vector<int> path2; bool dfs(TreeNode* node, vector<int>& path ,int o){ // 回溯法得到两个节点到根节点的路径 // if(node == nullptr) return; if(node->val == o){ path.push_back(o); return true; } if(node->left == nullptr && node->right == nullptr && node->val != 0){ return false; } if(node->left){ path.push_back(node->val); if( dfs(node->left, path,o) ) return true;; path.pop_back(); } if(node->right){ path.push_back(node->val); if( dfs(node->right, path, o) ) return true;; path.pop_back(); } return false; } int lowestCommonAncestor(TreeNode* root, int o1, int o2) { // write code here path1.clear(); path2.clear(); dfs(root, path1, o1); dfs(root, path2, o2); /* 测试回溯法结果是否正确 cout<< o1<<": "; for(int i: path1){ cout<< i<<' '; } cout<<endl; cout<< o2<<": "; for(int i: path2){ cout<< i<<' '; } cout<<endl; return 0; */ int result = 0; for(int i = 0; i<path1.size()&& i<path2.size(); i++){ if(path1[i] == path2[i]) result = path1[i]; else break; } return result; } };