解题思路:
递归搜索左右子树,如果左子树和右子树都不为空,说明最近父节点一定在根节点。
如果左子树为空,说明两个节点一定在右子树;
如果右子树为空,说明两个节点一定在左子树。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(root==NULL||root==p||root==q) return root;
TreeNode * left = lowestCommonAncestor(root->left,p,q);
TreeNode * right = lowestCommonAncestor(root->right,p,q);
return left==NULL?right:(right==NULL?left:root);
}
};