235 lowest common ancestor of a binary search tree

·data-structure-and-algorithm
#binary-tree

236. 二叉树的最近公共祖先

go:

/**

 * Definition for a binary tree node.

 * type TreeNode struct {

 *     Val   int

 *     Left  *TreeNode

 *     Right *TreeNode

 * }
 */

func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
	for root != nil {
        if p.Val < root.Val && q.Val < root.Val {
            root = root.Left
        } else if p.Val > root.Val && q.Val > root.Val {
            root = root.Right
        } else {
            return root
        }
    }
    
    return nil
}