题解 | #在二叉树中找到两个节点的最近公共祖先#
在二叉树中找到两个节点的最近公共祖先
http://www.nowcoder.com/practice/e0cc33a83afe4530bcec46eba3325116
package main
import . "nc_tools"
/*
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
/**
*
* @param root TreeNode类
* @param o1 int整型
* @param o2 int整型
* @return int整型
*/
func lowestCommonAncestor(root *TreeNode, p int, q int) int {
if root == nil {
return -1
}
if root.Val == p || root.Val == q {
return root.Val
}
left := lowestCommonAncestor(root.Left, p, q)
right := lowestCommonAncestor(root.Right, p, q)
if left > -1 && right > -1 {
return root.Val
}
if left > -1 {
return left
}
if right > -1 {
return right
}
return -1
}