对于一般树找其最近父节点,如果两个节点在某个节点的两侧,那么这个节点就是要求的最近父节点。否则要么在左子树中,要么在右子树中。
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if root == None:
return root
if root == p or root == q:
return root
left = self.lowestCommonAncestor(root.left,p,q)
right = self.lowestCommonAncestor(root.right,p,q)
if left == None and right != None:
return right
if left != None and right == None:
return left
if left != None and right != None:
return root
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if (!root) return NULL;
if (root == p || root == q) return root;
auto left = lowestCommonAncestor(root->left,p,q);
auto right = lowestCommonAncestor(root->right,p,q);
if (right && left) return root;
if (left) return left;
if (root) return right;
return NULL;
}
};