题解 | #二叉搜索树的最近公共祖先#比较路径/直接递归
二叉搜索树的最近公共祖先
https://www.nowcoder.com/practice/d9820119321945f588ed6a26f0a6991f
func lowestCommonAncestor( root *TreeNode , p int , q int ) int {
if root==nil{
return -1
}
if (p>=root.Val && q<=root.Val) || (p<=root.Val && q>=root.Val){
return root.Val
}else if p<=root.Val && q<=root.Val{
return lowestCommonAncestor(root.Left, p, q)
}else{
return lowestCommonAncestor(root.Right, p, q)
}
}
// func lowestCommonAncestor( root *TreeNode , p int , q int ) int {
// // write code here
// //获取两个节点的遍历路径,最后一个路径上的相同节点就是最近公共祖先
// path_p := getPath(root, p)
// path_q := getPath(root, q)
// index := -1
// for i,j := 0, 0; i<len(path_p) && j<len(path_q); i,j = i+1,j+1{
// if path_p[i] == path_q[j]{
// index = path_p[i]
// }else{
// break
// }
// }
// return index
// }
// func getPath(root *TreeNode, target int) (res []int){
// if root == nil{
// return
// }
// node := root
// for node.Val != target{
// res = append(res, node.Val)
// if node.Val < target{
// node = node.Right
// }else{
// node = node.Left
// }
// }
// res = append(res, node.Val)
// return res
// }

查看14道真题和解析