/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
class Solution {
public:
/**
*
* @param root TreeNode类
* @param o1 int整型
* @param o2 int整型
* @return int整型
*/
int lowestCommonAncestor(TreeNode* root, int o1, int o2) {
// write code here
if(root == NULL) // 遍历到底了,此路径不存在o1或者o2
return -1;
// 如果遍历到的节点的值和o1或者o2相等
// 返回节点的值
if(o1 == root->val || o2 == root->val) return root->val;
// 遍历左子树
int left = lowestCommonAncestor(root->left, o1, o2);
// 遍历右子树
int right = lowestCommonAncestor(root->right, o1, o2);
// left == -1 证明左子树中不存在o1或者o2,那么o1和o2必然存在于右子树中
if(left == -1)
return right;
// 同理left==-1
if(right == -1)
return left;
return root->val;
}
};