题解 | #在二叉树中找到两个节点的最近公共祖先# go
在二叉树中找到两个节点的最近公共祖先
http://www.nowcoder.com/practice/e0cc33a83afe4530bcec46eba3325116
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
} 
阿里云工作强度 644人发布