题解 | #在二叉树中找到两个节点的最近公共祖先# C++ 解法,后序从根节点回溯
在二叉树中找到两个节点的最近公共祖先
http://www.nowcoder.com/practice/e0cc33a83afe4530bcec46eba3325116
题解 | #在二叉树中找到两个节点的最近公共祖先#
C++ 解法,后序从根节点回溯
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
class Solution {
public:
/**
*
* @param root TreeNode类
* @param o1 int整型
* @param o2 int整型
* @return int整型
*/
TreeNode *dfs(TreeNode *root, int p, int q) {
if (root == nullptr || root->val == p || root->val == q) return root;
TreeNode *left = dfs(root->left, p, q);
TreeNode *right = dfs(root->right, p, q);
if (left && right) return root;
if (left) return left;
if (right) return right;
return nullptr;
}
int lowestCommonAncestor(TreeNode* root, int o1, int o2) {
TreeNode *ans = dfs(root, o1, o2);
return ans->val;
}
};
查看7道真题和解析