Golang Leetcode 235. Lowest Common Ancestor of a Binary Search Tree.go

时间:2022-06-19
本文章向大家介绍Golang Leetcode 235. Lowest Common Ancestor of a Binary Search Tree.go,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

版权声明:原创勿转 https://blog.csdn.net/anakinsun/article/details/89043473

思路

寻找最近的公共祖先,当root非空时可以区分为三种情况:1)两个节点均在root的左子树,此时对root->left递归求解;2)两个节点均在root的右子树,此时对root->right递归求解;3)两个节点分别位于root的左右子树,此时LCA为root。

code

type TreeNode struct {
	Val   int
	Left  *TreeNode
	Right *TreeNode
}

func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {

	if root == nil {
		return nil
	}

	for root != nil {
		if p.Val > root.Val && q.Val > root.Val {
			root = root.Right
		} else if p.Val < root.Val && q.Val < root.Val {
			root = root.Left
		} else {
			return root
		}
	}
	return nil

}