go
/**
*
* @param root TreeNode类
* @param o1 int整型
* @param o2 int整型
* @return int整型
*/
func lowestCommonAncestor( root *TreeNode , o1 int , o2 int ) int {
// write code here
if root == nil {
return -1
}
var isParent func(root *TreeNode , o1 int , o2 int) *TreeNode
isParent = func(root *TreeNode, o1, o2 int) *TreeNode {
if root == nil {// 遇到null,返回null 没有LCA
return root
}
// 遇到o1或o2,直接返回当前节点
if root.Val == o1 || root.Val == o2 {
return root
}
// 非null 非o1 非o2,则递归左右子树
left := isParent(root.Left, o1, o2)
right := isParent(root.Right, o1, o2)
// 根据递归的结果,决定谁是LCA
if left == nil {
return right
}
if right == nil {
return left
}
return root
}
node := isParent(root, o1, o2)
if node != nil {
return node.Val
}
return -1
} 
京公网安备 11010502036488号