题解 | #在二叉树中找到两个节点的最近公共祖先#
在二叉树中找到两个节点的最近公共祖先
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整型 */ bool findAncestor(TreeNode* tmp, const int& o1, const int& o2, int& ret) { if (ret != -1) return true; if (tmp == nullptr) return false; if (tmp->val == o1 || tmp->val == o2) { bool find = findAncestor(tmp->left, o1, o2, ret); if (find) { ret = tmp->val; return true; } find = findAncestor(tmp->right, o1, o2, ret); if (find) { ret = tmp->val; return true; } return true; } bool find1 = findAncestor(tmp->left, o1, o2, ret); if (ret != -1) return true; bool find2 = findAncestor(tmp->right, o1, o2, ret); if (ret != -1) return true; if (find1 && find2) { ret = tmp->val; return true; } else if (find1 || find2) { return true; } return false; } int lowestCommonAncestor(TreeNode* root, int o1, int o2) { // write code here int ret = -1; findAncestor(root, o1, o2, ret); return ret; } };