题目链接: 剑指 Offer 68 - I. 二叉搜索树的最近公共祖先
题目描述:
给定一个二叉搜索树, 找到该树中两个指定节点的最近公共祖先。
解法思路:
代码:
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
if p.Val < root.Val && q.Val < root.Val{
return lowestCommonAncestor(root.Left,p,q)
}
if p.Val > root.Val && q.Val > root.Val{
return lowestCommonAncestor(root.Right,p,q)
}
return root
}