# 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:ifrootisNoneorrootin[p,q]:returnrootleft=self.lowestCommonAncestor(root.left,p,q)right=self.lowestCommonAncestor(root.right,p,q)returnrootifleftandrightelseleftorright
1 2 3 4 5 6 7 8 910111213141516171819
/** * 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;}TreeNodeleft=lowestCommonAncestor(root.left,p,q);TreeNoderight=lowestCommonAncestor(root.right,p,q);returnleft==null?right:(right==null?left:root);}}
1 2 3 4 5 6 7 8 91011121314151617181920
/** * 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||root==p||root==q){returnroot;}TreeNode*left=lowestCommonAncestor(root->left,p,q);TreeNode*right=lowestCommonAncestor(root->right,p,q);returnleft&&right?root:(left?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*TreeNode,p*TreeNode,q*TreeNode)*TreeNode{ifroot==nil||root==p||root==q{returnroot}left:=lowestCommonAncestor(root.Left,p,q)right:=lowestCommonAncestor(root.Right,p,q)ifleft==nil{returnright}ifright==nil{returnleft}returnroot}
1 2 3 4 5 6 7 8 9101112131415161718192021
/** * Definition for a binary tree node. * function TreeNode(val) { * this.val = val; * this.left = this.right = null; * } *//** * @param {TreeNode} root * @param {TreeNode} p * @param {TreeNode} q * @return {TreeNode} */varlowestCommonAncestor=function(root,p,q){if(!root||root===p||root===q){returnroot;}constleft=lowestCommonAncestor(root.left,p,q);constright=lowestCommonAncestor(root.right,p,q);returnleft&&right?root:left||right;};