# Definition for a binary tree node.# class TreeNode:# def __init__(self, x):# self.val = x# self.left = None# self.right = NoneclassSolution:deflowestCommonAncestor(self,root:"TreeNode",p:"TreeNode",q:"TreeNode")->"TreeNode":ifrootin(None,p,q):returnrootleft=self.lowestCommonAncestor(root.left,p,q)right=self.lowestCommonAncestor(root.right,p,q)returnrootifleftandrightelse(leftorright)
1 2 3 4 5 6 7 8 910111213141516171819202122
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */classSolution{publicTreeNodelowestCommonAncestor(TreeNoderoot,TreeNodep,TreeNodeq){if(root==null||root==p||root==q){returnroot;}varleft=lowestCommonAncestor(root.left,p,q);varright=lowestCommonAncestor(root.right,p,q);if(left!=null&&right!=null){returnroot;}returnleft==null?right:left;}}
1 2 3 4 5 6 7 8 91011121314151617181920212223
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */classSolution{public:TreeNode*lowestCommonAncestor(TreeNode*root,TreeNode*p,TreeNode*q){if(root==nullptr||root==p||root==q){returnroot;}autoleft=lowestCommonAncestor(root->left,p,q);autoright=lowestCommonAncestor(root->right,p,q);if(left&&right){returnroot;}returnleft?left:right;}};
1 2 3 4 5 6 7 8 910111213141516171819202122
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */funclowestCommonAncestor(root,p,q*TreeNode)*TreeNode{ifroot==nil||root==p||root==q{returnroot}left:=lowestCommonAncestor(root.Left,p,q)right:=lowestCommonAncestor(root.Right,p,q)ifleft!=nil&&right!=nil{returnroot}ifleft!=nil{returnleft}returnright}