题解 | #在二叉树中找到两个节点的最近公共祖先#
在二叉树中找到两个节点的最近公共祖先
http://www.nowcoder.com/practice/e0cc33a83afe4530bcec46eba3325116
package main
import . "nc_tools"
func lowestCommonAncestor( root *TreeNode , o1 int , o2 int ) int {
if root == nil {
return -1
}
node := isParent(root,o1,o2)
if node != nil {
return node.Val
}
return -1
}
func isParent(root *TreeNode, o1, o2 int) *TreeNode {
if root == nil {
return root
}
if root.Val == o1 || root.Val == o2 {
return root
}
left := isParent(root.Left, o1, o2)
right := isParent(root.Right, o1, o2)
if left == nil {
return right
}
if right == nil {
return left
}
return root
}
嘉士伯公司氛围 308人发布