题解 | #在二叉树中找到两个节点的最近公共祖先#(递归左右子树,寻找并返回找到的节点)
在二叉树中找到两个节点的最近公共祖先
http://www.nowcoder.com/practice/e0cc33a83afe4530bcec46eba3325116
应该说明查找的两个节点不能重复吧。很容易引起歧义。
class Solution {
public:
int lowestCommonAncestor(TreeNode* root, int o1, int o2) {
return dfs(root, o1, o2)->val;
}
TreeNode* dfs(TreeNode* root, const int& p, const int& q){
if(!root || root->val == p || root->val == q) return root;
TreeNode* ls = dfs(root->left, p, q);
TreeNode* rs = dfs(root->right, p, q);
if(ls == NULL) return rs; // 左右节点祖先在右边
if(rs == NULL) return ls; // 左右节点祖先在左边
return root;
}
};